天天看点

Django装饰器的使用方法,自定义登录验证装饰器Django装饰器的使用方法(登录验证)

Django装饰器的使用方法(登录验证)

1.自定义登录装饰器

from django.http import HttpResponseRedirect
def check_login(func):
    def wrapper(req):
        if 'user' not in req.session:
            path = req.path
            return HttpResponseRedirect('/login?pre_url=' + path)  #用于记录访问历史页面,便于登录后跳转
        else:
            return func(req)
    return wrapper
           

2.装饰器的使用

a.装饰函数

view.py

from lib.my_decorator import check_login  # 引入自定义的装饰器

@check_login  # 登录验证
def my_function(req):
    return render(req, 'index.html')
           
b.装饰类

view.py

from lib.my_decorator import check_login
from django.views import View
from django.utils.decorators import method_decorator

class MyView(View):

    @method_decorator(check_login)   # 装饰类的视图
    def dispatch(self, *args, **kwargs):
        return super(AccountView, self).dispatch(*args, **kwargs)

    def get(self, req):
        return render(req, 'index.html')
           
c.装饰URL

urls.py

from app_name.view import MyView
from lib.my_decorator import check_login

urlpatterns = [
	url(r'^index/$', check_login(MyView.as_view()), name='index'),  # view.py中还保持一般的写法就可以
]
           

参考资料:

链接: https://www.jb51.net/article/128954.htm