本文整理汇总了Python中django.middleware.csrf.get_token方法的典型用法代码示例。如果您正苦于以下问题:Python csrf.get_token方法的具体用法?Python csrf.get_token怎么用?Python csrf.get_token使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.middleware.csrf
的用法示例。
在下文中一共展示了csrf.get_token方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: render_content_fragments
# 需要导入模块: from django.middleware import csrf [as 别名]
# 或者: from django.middleware.csrf import get_token [as 别名]
def render_content_fragments(fragments, placeholders, request):
csrf_token = get_token(request)
if csrf_token is None:
csrf_token = ''
content = []
for fragment_type, fragment_content in fragments:
if fragment_type == FragmentType.CONTENT:
content.append(fragment_content)
elif fragment_type == FragmentType.PLACEHOLDER:
try:
placeholder_content = str(placeholders[fragment_content]).encode()
except KeyError:
placeholder_content = b''
content.append(placeholder_content)
elif fragment_type == FragmentType.CSRFTOKEN:
content.append(csrf_token.encode())
else:
raise ValueError('Invalid fragment type: {}'.format(fragment_type))
return b''.join(content)
示例2: csrf
# 需要导入模块: from django.middleware import csrf [as 别名]
# 或者: from django.middleware.csrf import get_token [as 别名]
def csrf(request):
"""
Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if
it has not been provided by either a view decorator or the middleware
"""
def _get_val():
token = get_token(request)
if token is None:
# In order to be able to provide debugging info in the
# case of misconfiguration, we use a sentinel value
# instead of returning an empty dict.
return 'NOTPROVIDED'
else:
return smart_text(token)
_get_val = lazy(_get_val, six.text_type)
return {'csrf_token': _get_val()}
示例3: csrf
# 需要导入模块: from django.middleware import csrf [as 别名]
# 或者: from django.middleware.csrf import get_token [as 别名]
def csrf(request):
"""
Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if
it has not been provided by either a view decorator or the middleware
"""
def _get_val():
token = get_token(request)
if token is None:
# In order to be able to provide debugging info in the
# case of misconfiguration, we use a sentinel value
# instead of returning an empty dict.
return 'NOTPROVIDED'
else:
return token
return {'csrf_token': SimpleLazyObject(_get_val)}
示例4: csrf
# 需要导入模块: from django.middleware import csrf [as 别名]
# 或者: from django.middleware.csrf import get_token [as 别名]
def csrf(request):
"""
Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if
it has not been provided by either a view decorator or the middleware
"""
def _get_val():
token = get_token(request)
if token is None:
# In order to be able to provide debugging info in the
# case of misconfiguration, we use a sentinel value
# instead of returning an empty dict.
return 'NOTPROVIDED'
else:
return force_text(token)
return {'csrf_token': SimpleLazyObject(_get_val)}
示例5: csrfform
# 需要导入模块: from django.middleware import csrf [as 别名]
# 或者: from django.middleware.csrf import get_token [as 别名]
def csrfform(request):
response = """<p>CSRF Success guessing game...</p>
<form method="POST">
<p><label for="guess">Input Guess</label>
<input type="text" name="guess" size="40" id="guess"/></p>
<input type="hidden" name="csrfmiddlewaretoken"
value="__token__"/>
<input type="submit"/>
</form>"""
token = get_token(request)
response = response.replace('__token__', html.escape(token))
response += dumpdata('POST', request.POST)
return HttpResponse(response)
# Call as checkguess('42')
示例6: csrf
# 需要导入模块: from django.middleware import csrf [as 别名]
# 或者: from django.middleware.csrf import get_token [as 别名]
def csrf(request):
"""
Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if
it has not been provided by either a view decorator or the middleware
"""
def _get_val():
token = get_token(request)
if token is None:
# In order to be able to provide debugging info in the
# case of misconfiguration, we use a sentinel value
# instead of returning an empty dict.
return 'NOTPROVIDED'
else:
return smart_text(token)
_get_val = lazy(_get_val, six.text_type)
return {'csrf_token': _get_val() }
示例7: csrf
# 需要导入模块: from django.middleware import csrf [as 别名]
# 或者: from django.middleware.csrf import get_token [as 别名]
def csrf(request):
"""
Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if
it has not been provided by either a view decorator or the middleware
"""
def _get_val():
token = get_token(request)
if token is None:
# In order to be able to provide debugging info in the
# case of misconfiguration, we use a sentinel value
# instead of returning an empty dict.
return 'NOTPROVIDED'
else:
return smart_text(token)
return {'csrf_token': SimpleLazyObject(_get_val)}
示例8: render_column
# 需要导入模块: from django.middleware import csrf [as 别名]
# 或者: from django.middleware.csrf import get_token [as 别名]
def render_column(self, row, column):
instockclass = add_asset_display_class(row)
if column == 'name':
extra_string = ''
if row.has_attachments():
extra_string += ' <i class="fa fa-paperclip" title="Attachment(s)"></i>'
if row.has_records():
extra_string += ' <i class="fa fa-book" title="Record(s)"></i>'
return row.name + extra_string
if column == 'quantity':
return str("<span class=" + instockclass + ">%s</span>" % row.quantity)
elif column == 'last_modified':
return str("<span class='sort'>%s</span>%s" % (row.last_modified, row.last_modified.strftime("%b %d, %Y")))
elif column == 'actions':
return '<form class="lineform" method="POST" action=' +\
reverse('inventory:delete_asset', kwargs={'asset_id': row.id}) + '>' +\
'<input type="hidden" name="csrfmiddlewaretoken" value="' + get_token(self.request) + '">' +\
'<button type="submit" class="btn confirm-submit" title="Hide asset" data-submit-action="remove this asset">' +\
'<i class="fa fa-trash-o"></i>' +\
'</button>' +\
'</form>' +\
'<a class="lineform" href="' + reverse('inventory:add_change_record', kwargs={'asset_slug': row.slug}) +'">' +\
'<button type="submit" class="btn" title="Add change record">' +\
'<i class="fa fa-book"></i>' +\
'</button>' +\
'</a>' +\
'<a class="lineform" href="' + reverse('inventory:edit_asset', kwargs={'asset_slug': row.slug}) + '">' +\
'<button type="submit" class="btn" title="Edit asset">' +\
'<i class="fa fa-edit"></i>' +\
'</button>' +\
'</a>' +\
'<a class="lineform" href="' + reverse('inventory:view_asset', kwargs={'asset_slug': row.slug}) + '">' +\
'<button type="submit" class="btn" title="View asset">' +\
'<i class="fa fa-eye"></i>' +\
'</button>' +\
'</a>'
else:
return super(InventoryDataJSON, self).render_column(row, column)
示例9: csrf_input
# 需要导入模块: from django.middleware import csrf [as 别名]
# 或者: from django.middleware.csrf import get_token [as 别名]
def csrf_input(request):
return format_html(
'<input type="hidden" name="csrfmiddlewaretoken" value="{}" />',
get_token(request))
示例10: microsoft
# 需要导入模块: from django.middleware import csrf [as 别名]
# 或者: from django.middleware.csrf import get_token [as 别名]
def microsoft(request):
""" Adds global template variables for microsoft_auth """
login_type = None
if config.MICROSOFT_AUTH_LOGIN_TYPE == LOGIN_TYPE_XBL:
login_type = _("Xbox Live")
else:
login_type = _("Microsoft")
if config.DEBUG: # pragma: no branch
try:
current_domain = Site.objects.get_current(request).domain
except Site.DoesNotExist:
logger.warning(
"\nWARNING:\nThe domain configured for the sites framework "
"does not match the domain you are accessing Django with. "
"Microsoft authentication may not work.\n"
)
else:
do_warning = get_scheme(
request
) == "http" and not current_domain.startswith("localhost")
if do_warning: # pragma: no branch
logger.warning(
"\nWARNING:\nYou are not using HTTPS. Microsoft "
"authentication only works over HTTPS unless the hostname "
"for your `redirect_uri` is `localhost`\n"
)
# initialize Microsoft client using CSRF token as state variable
signer = TimestampSigner()
state = signer.sign(get_token(request))
microsoft = MicrosoftClient(state=state, request=request)
auth_url = microsoft.authorization_url()[0]
return {
"microsoft_login_enabled": config.MICROSOFT_AUTH_LOGIN_ENABLED,
"microsoft_authorization_url": mark_safe(auth_url), # nosec
"microsoft_login_type_text": login_type,
}
示例11: get_zoom_sid
# 需要导入模块: from django.middleware import csrf [as 别名]
# 或者: from django.middleware.csrf import get_token [as 别名]
def get_zoom_sid(request: HttpRequest) -> str:
# This is used to prevent CSRF attacks on the Zoom OAuth
# authentication flow. We want this value to be unpredictable and
# tied to the session, but we don’t want to expose the main CSRF
# token directly to the Zoom server.
csrf.get_token(request)
# Use 'mark_sanitized' to cause Pysa to ignore the flow of user controlled
# data out of this function. 'request.META' is indeed user controlled, but
# post-HMAC ouptut is no longer meaningfully controllable.
return mark_sanitized(
""
if getattr(request, "_dont_enforce_csrf_checks", False)
else salted_hmac("Zulip Zoom sid", request.META["CSRF_COOKIE"]).hexdigest()
)
示例12: csrf_input
# 需要导入模块: from django.middleware import csrf [as 别名]
# 或者: from django.middleware.csrf import get_token [as 别名]
def csrf_input(request):
return format_html(
'<input type="hidden" name="csrfmiddlewaretoken" value="{}">',
get_token(request))
示例13: list
# 需要导入模块: from django.middleware import csrf [as 别名]
# 或者: from django.middleware.csrf import get_token [as 别名]
def list(self, request, *args, **kwargs):
return Response({
'is_authenticated': request.user.is_authenticated,
'csrf_token': csrf.get_token(request),
})
示例14: login
# 需要导入模块: from django.middleware import csrf [as 别名]
# 或者: from django.middleware.csrf import get_token [as 别名]
def login(self, request, *args, **kwargs):
# django-rest-framework doesn't do this for logged out requests
SessionAuthentication().enforce_csrf(request)
if request.user.is_authenticated:
raise ParseError(_('Log out first.'))
data = get_api_post_data(request)
if 'token' in data:
try:
token = Token.get_by_token(data['token'])
except Token.DoesNotExist:
raise PermissionDenied(_('This token does not exist or is no longer valid.'))
user = token.user
elif 'username' in data:
form = AuthenticationForm(request, data=data)
if not form.is_valid():
raise ParseError(form.errors)
user = form.user_cache
else:
raise ParseError(_('You need to send a token or username and password.'))
login(request, user)
return Response({
'detail': _('Login successful.'),
'csrf_token': csrf.get_token(request),
})
示例15: get_token
# 需要导入模块: from django.middleware import csrf [as 别名]
# 或者: from django.middleware.csrf import get_token [as 别名]
def get_token(self, request, *args, **kwargs):
# django-rest-framework doesn't do this for logged out requests
SessionAuthentication().enforce_csrf(request)
data = get_api_post_data(request)
form = AuthenticationForm(request, data=data)
if not form.is_valid():
raise ParseError(form.errors)
token = form.user_cache.login_tokens.create()
return Response({
'token': token.get_token(),
})