zoukankan      html  css  js  c++  java
  • django 强制登录最佳实践

    参考:

    https://python-programming.courses/recipes/django-require-authentication-pages/

    即通过中间件来做AOP拦截。不用每个函数每个类加修饰器/MixIn。

    1. 在某个处理用户相关的模块中添加middleware.py, 内容如下:

    from django.http import HttpResponseRedirect
    from django.conf import settings
    from re import compile
    
    EXEMPT_URLS = [compile(settings.LOGIN_URL.lstrip('/'))]
    if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
        EXEMPT_URLS += [compile(expr) for expr in settings.LOGIN_EXEMPT_URLS]
    
    class LoginRequiredMiddleware:
        """
        Middleware that requires a user to be authenticated to view any page other
        than LOGIN_URL. Exemptions to this requirement can optionally be specified
        in settings via a list of regular expressions in LOGIN_EXEMPT_URLS (which
        you can copy from your urls.py).
    
        Requires authentication middleware and template context processors to be
        loaded. You'll get an error if they aren't.
        """
        def process_request(self, request):
            assert hasattr(request, 'user'), "The Login Required middleware
     requires authentication middleware to be installed. Edit your
     MIDDLEWARE_CLASSES setting to insert
     'django.contrib.auth.middlware.AuthenticationMiddleware'. If that doesn't
     work, ensure your TEMPLATE_CONTEXT_PROCESSORS setting includes
     'django.core.context_processors.auth'."
            if not request.user.is_authenticated():
                path = request.path_info.lstrip('/')
                if not any(m.match(path) for m in EXEMPT_URLS):
                    return HttpResponseRedirect(settings.LOGIN_URL)

    2. 使用此middleware

    settings.py 中的 middleware_classes的最后添加一行

    MIDDLEWARE_CLASSES = [
        ...   
        'myapplication.middleware.LoginRequiredMiddleware',
    ]

    3. 如果有要放水的url,通过settings.py中添加LOGIN_EXEMPT_URLS(tuple of string)变量设置,例如:

    LOGIN_EXEMPT_URLS = (
        r'^accounts/signup/$',
    )
  • 相关阅读:
    java09-8大基本类型的包装类、装箱拆箱
    java08-枚举
    类加载-双亲委托机制
    java虚拟机05-虚拟机加载类机制&类加载器
    java虚拟机04-内存分配与回收策略
    java-07 内部类、匿名内部类、局部内部类、lambda
    从0开始的Python学习012数据结构&对象与类
    从0开始的Python学习011模块
    从0开始的Python学习010return语句&DocStrings
    从0开始的Python学习009参数
  • 原文地址:https://www.cnblogs.com/Tommy-Yu/p/6163571.html
Copyright © 2011-2022 走看看