当前位置: 首页>>代码示例>>Python>>正文


Python csrf.get_token方法代码示例

本文整理汇总了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) 
开发者ID:PrivacyScore,项目名称:PrivacyScore,代码行数:22,代码来源:__init__.py

示例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()} 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:19,代码来源:context_processors.py

示例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)} 
开发者ID:reBiocoder,项目名称:bioforum,代码行数:18,代码来源:context_processors.py

示例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)} 
开发者ID:Yeah-Kun,项目名称:python,代码行数:18,代码来源:context_processors.py

示例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') 
开发者ID:csev,项目名称:dj4e-samples,代码行数:18,代码来源:views.py

示例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() } 
开发者ID:blackye,项目名称:luscan-devel,代码行数:19,代码来源:context_processors.py

示例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)} 
开发者ID:drexly,项目名称:openhgsenti,代码行数:18,代码来源:context_processors.py

示例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 += ' &nbsp; <i class="fa fa-paperclip" title="Attachment(s)"></i>'
            if row.has_records():
                extra_string += ' &nbsp; <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) 
开发者ID:sfu-fas,项目名称:coursys,代码行数:41,代码来源:views.py

示例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)) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:6,代码来源:utils.py

示例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,
    } 
开发者ID:AngellusMortis,项目名称:django_microsoft_auth,代码行数:40,代码来源:context_processors.py

示例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()
    ) 
开发者ID:zulip,项目名称:zulip,代码行数:17,代码来源:video_calls.py

示例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)) 
开发者ID:PacktPublishing,项目名称:Hands-On-Application-Development-with-PyCharm,代码行数:6,代码来源:utils.py

示例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),
        }) 
开发者ID:c3nav,项目名称:c3nav,代码行数:7,代码来源:api.py

示例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),
        }) 
开发者ID:c3nav,项目名称:c3nav,代码行数:31,代码来源:api.py

示例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(),
        }) 
开发者ID:c3nav,项目名称:c3nav,代码行数:17,代码来源:api.py


注:本文中的django.middleware.csrf.get_token方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。