本文整理汇总了Python中django.middleware.csrf.get_token方法的典型用法代码示例。如果您正苦于以下问题:Python csrf.get_token方法的具体用法?Python csrf.get_token怎么用?Python csrf.get_token使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在模块django.middleware.csrf的用法示例。
在下文中一共展示了csrf.get_token方法的22个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: render_content_fragments
点赞 6
# 需要导入模块: 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)
开发者ID:PrivacyScore,项目名称:PrivacyScore,代码行数:22,
示例2: csrf
点赞 6
# 需要导入模块: 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()}
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:19,
示例3: csrf
点赞 6
# 需要导入模块: 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)}
开发者ID:reBiocoder,项目名称:bioforum,代码行数:18,
示例4: csrf
点赞 6
# 需要导入模块: 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)}
开发者ID:Yeah-Kun,项目名称:python,代码行数:18,
示例5: csrfform
点赞 6
# 需要导入模块: from django.middleware import csrf [as 别名]
# 或者: from django.middleware.csrf import get_token [as 别名]
def csrfform(request):
response = """
CSRF Success guessing game...
Input Guess
value="__token__"/>
"""token = get_token(request)
response = response.replace('__token__', html.escape(token))
response += dumpdata('POST', request.POST)
return HttpResponse(response)
# Call as checkguess('42')
开发者ID:csev,项目名称:dj4e-samples,代码行数:18,
示例6: csrf
点赞 6
# 需要导入模块: 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() }
开发者ID:blackye,项目名称:luscan-devel,代码行数:19,
示例7: csrf
点赞 6
# 需要导入模块: 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)}
开发者ID:drexly,项目名称:openhgsenti,代码行数:18,
示例8: render_column
点赞 5
# 需要导入模块: 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 += ' '
if row.has_records():
extra_string += ' '
return row.name + extra_string
if column == 'quantity':
return str("%s" % row.quantity)
elif column == 'last_modified':
return str("%s%s" % (row.last_modified, row.last_modified.strftime("%b %d, %Y")))
elif column == 'actions':
return '
' +\'' +\
'' +\
'' +\
'' +\
'
' +\'' +\
'' +\
'' +\
'' +\
'' +\
'' +\
'' +\
'' +\
'' +\
'' +\
'' +\
'' +\
'' +\
'' +\
''
else:
return super(InventoryDataJSON, self).render_column(row, column)
开发者ID:sfu-fas,项目名称:coursys,代码行数:41,
示例9: csrf_input
点赞 5
# 需要导入模块: from django.middleware import csrf [as 别名]
# 或者: from django.middleware.csrf import get_token [as 别名]
def csrf_input(request):
return format_html(
'',
get_token(request))
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:6,
示例10: microsoft
点赞 5
# 需要导入模块: 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,
}
开发者ID:AngellusMortis,项目名称:django_microsoft_auth,代码行数:40,
示例11: get_zoom_sid
点赞 5
# 需要导入模块: 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()
)
开发者ID:zulip,项目名称:zulip,代码行数:17,
示例12: csrf_input
点赞 5
# 需要导入模块: from django.middleware import csrf [as 别名]
# 或者: from django.middleware.csrf import get_token [as 别名]
def csrf_input(request):
return format_html(
'',
get_token(request))
开发者ID:PacktPublishing,项目名称:Hands-On-Application-Development-with-PyCharm,代码行数:6,
示例13: list
点赞 5
# 需要导入模块: 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),
})
开发者ID:c3nav,项目名称:c3nav,代码行数:7,
示例14: login
点赞 5
# 需要导入模块: 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),
})
开发者ID:c3nav,项目名称:c3nav,代码行数:31,
示例15: get_token
点赞 5
# 需要导入模块: 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(),
})
开发者ID:c3nav,项目名称:c3nav,代码行数:17,
示例16: logout
点赞 5
# 需要导入模块: from django.middleware import csrf [as 别名]
# 或者: from django.middleware.csrf import get_token [as 别名]
def logout(self, request, *args, **kwargs):
# django-rest-framework doesn't do this for logged out requests
SessionAuthentication().enforce_csrf(request)
if not request.user.is_authenticated:
return ParseError(_('Not logged in.'))
logout(request)
return Response({
'detail': _('Logout successful.'),
'csrf_token': csrf.get_token(request),
})
开发者ID:c3nav,项目名称:c3nav,代码行数:15,
示例17: process_response
点赞 5
# 需要导入模块: from django.middleware import csrf [as 别名]
# 或者: from django.middleware.csrf import get_token [as 别名]
def process_response(self, request, response):
if isinstance(response, TemplateResponse) and response.template_name[0] in self.needs_update:
content = response.content
token = get_token(request)
replace = b"name=\'csrfmiddlewaretoken\' value=\'" + token.encode() + b"\'"
regex = re.compile(br"name=\'csrfmiddlewaretoken\'\s*value=\'\w*\'")
response.content = re.sub(regex, replace, content)
return response
开发者ID:iguana-project,项目名称:iguana,代码行数:10,
示例18: test_get_csrf_token
点赞 5
# 需要导入模块: from django.middleware import csrf [as 别名]
# 或者: from django.middleware.csrf import get_token [as 别名]
def test_get_csrf_token(self):
# testing that csrf token is returned on GET request to mail api
response = self.client.get('/api/mail/send_mail/')
request = response.wsgi_request
csrf_token = csrf.get_token(request)
开发者ID:openstax,项目名称:openstax-cms,代码行数:7,
示例19: send_contact_message
点赞 5
# 需要导入模块: from django.middleware import csrf [as 别名]
# 或者: from django.middleware.csrf import get_token [as 别名]
def send_contact_message(request):
if request.method == 'POST':
name = request.POST.get("from_name", "")
from_name = name.replace(',', '')
from_address = request.POST.get("from_address", "")
from_string = '{} '.format(from_name, from_address)
subject = request.POST.get("subject", "")
message_body = request.POST.get("message_body", "")
# Add subject: to_address to this dict to add a new email address.
# Subject will map to the email being sent to to prevent misuse of our email server.
mails = Mail.objects.all()
emails = {mail.subject: mail.to_address for mail in mails}
try:
to_address = emails[subject].split(',')
email = EmailMessage(subject,
message_body,
'noreply@openstax.org',
to_address,
reply_to=[from_string])
email.send()
except KeyError:
logging.error("EMAIL FAILED TO SEND: subject:{}")
if subject == "Bulk Order": # if this is a bulk order, send them to a special confirmation page
return redirect('/confirmation/bulk-order')
else: #otherwise, send them to the contact confirmation page
return redirect('/confirmation/contact')
# if this is not posting a message, let's send the csfr token back
else:
csrf_token = csrf.get_token(request)
data = {'csrf_token': csrf_token}
return JsonResponse(data)
开发者ID:openstax,项目名称:openstax-cms,代码行数:38,
示例20: csrf_token_error_handler
点赞 5
# 需要导入模块: from django.middleware import csrf [as 别名]
# 或者: from django.middleware.csrf import get_token [as 别名]
def csrf_token_error_handler(request, **kwargs):
"""This error handler accesses the CSRF token."""
template = Template(get_token(request))
return HttpResponse(template.render(Context()), status=599)
开发者ID:nesdis,项目名称:djongo,代码行数:6,
示例21: test_login_csrf_rotate
点赞 5
# 需要导入模块: from django.middleware import csrf [as 别名]
# 或者: from django.middleware.csrf import get_token [as 别名]
def test_login_csrf_rotate(self):
"""
Makes sure that a login rotates the currently-used CSRF token.
"""
# Do a GET to establish a CSRF token
# The test client isn't used here as it's a test for middleware.
req = HttpRequest()
CsrfViewMiddleware().process_view(req, LoginView.as_view(), (), {})
# get_token() triggers CSRF token inclusion in the response
get_token(req)
resp = LoginView.as_view()(req)
resp2 = CsrfViewMiddleware().process_response(req, resp)
csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, None)
token1 = csrf_cookie.coded_value
# Prepare the POST request
req = HttpRequest()
req.COOKIES[settings.CSRF_COOKIE_NAME] = token1
req.method = "POST"
req.POST = {'username': 'testclient', 'password': 'password', 'csrfmiddlewaretoken': token1}
# Use POST request to log in
SessionMiddleware().process_request(req)
CsrfViewMiddleware().process_view(req, LoginView.as_view(), (), {})
req.META["SERVER_NAME"] = "testserver" # Required to have redirect work in login view
req.META["SERVER_PORT"] = 80
resp = LoginView.as_view()(req)
resp2 = CsrfViewMiddleware().process_response(req, resp)
csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, None)
token2 = csrf_cookie.coded_value
# Check the CSRF token switched
self.assertNotEqual(token1, token2)
开发者ID:nesdis,项目名称:djongo,代码行数:35,
示例22: csrf
点赞 5
# 需要导入模块: from django.middleware import csrf [as 别名]
# 或者: from django.middleware.csrf import get_token [as 别名]
def csrf(request):
"""Get the CSRF token for the authenticated user."""
if request.method != "POST":
return HttpResponseNotAllowed(["POST"])
if (
request.user is None
or not request.user.is_authenticated
or not request.user.is_active
):
return HttpResponseForbidden()
token = get_token(request)
# Don't mark the CSRF as used. If not done, Django will cycle the
# CSRF and the returned CSRF will be un-usable.
request.META.pop("CSRF_COOKIE_USED", None)
return JsonResponse({"csrf": token})
开发者ID:maas,项目名称:maas,代码行数:17,
注:本文中的django.middleware.csrf.get_token方法示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。