您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

使Django的login_required为默认值的最佳方法

使Django的login_required为默认值的最佳方法

中间件可能是你最好的选择。我过去使用过这段代码,是在其他地方的代码段中进行了修改

import re

from django.conf import settings
from django.contrib.auth.decorators import login_required


class RequireLoginMiddleware(object):
    """
    Middleware component that wraps the login_required decorator around
    matching URL patterns. To use, add the class to MIDDLEWARE_CLASSES and
    define LOGIN_required_URLS and LOGIN_required_URLS_EXCEPTIONS in your
    settings.py. For example:
    ------
    LOGIN_required_URLS = (
        r'/topsecret/(.*)$',
    )
    LOGIN_required_URLS_EXCEPTIONS = (
        r'/topsecret/login(.*)$',
        r'/topsecret/logout(.*)$',
    )
    ------
    LOGIN_required_URLS is where you define URL patterns; each pattern must
    be a valid regex.

    LOGIN_required_URLS_EXCEPTIONS is, conversely, where you explicitly
    define any exceptions (like login and logout URLs).
    """
    def __init__(self):
        self.required = tuple(re.compile(url) for url in settings.LOGIN_required_URLS)
        self.exceptions = tuple(re.compile(url) for url in settings.LOGIN_required_URLS_EXCEPTIONS)

    def process_view(self, request, view_func, view_args, view_kwargs):
        # No need to process URLs if user already logged in
        if request.user.is_authenticated():
            return None

        # An exception match should immediately return None
        for url in self.exceptions:
            if url.match(request.path):
                return None

        # Requests matching a restricted URL pattern are returned
        # wrapped with the login_required decorator
        for url in self.required:
            if url.match(request.path):
                return login_required(view_func)(request, *view_args, **view_kwargs)

        # Explicitly return None for all non-matching requests
        return None

然后在settings.py中,列出你要保护的基本URL:

LOGIN_required_URLS = (
    r'/private_stuff/(.*)$',
    r'/login_required/(.*)$',
)

只要你的站点遵循要求身份验证的页面的URL约定,此模型就可以工作。如果这不是一对一的适合,你可以选择修改中间件以更紧密地适应你的情况。

我喜欢这种方法-除了消除了用@login_required修饰符乱扔代码库的必要性之外-如果身份验证方案发生更改,你还有一个地方可以进行全局更改。

Go 2022/1/1 18:24:16 有370人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶