栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

import refrom django.conf import settingsfrom django.contrib.auth.decorators import login_requiredclass 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
修饰符乱扔代码库的必要性之外-如果身份验证方案发生更改,你还有一个地方可以进行全局更改。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/400419.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号