cookie
登录index时,判断用户是否登录过(cookie是否有效)
方法一:
在views中设置
def index(request):
if request.method == 'GET':
# get ticket from cookie
ticket = request.COOKIES.get('ticket')
# get values from UserTicket by ticket
user_ticket = UserTicket.objects.filter(ticket=ticket).first()
if user_ticket:
# get user who login
user = user_ticket
return render(request, 'index.html', {'user': user})
else:
return HttpResponseRedirect(reverse('users:login'))
方法二:
使用装饰器
需要新建目录utils,utils下有2个py文件
在functions.py文件中写修饰器代码
def is_login(func):
def check(request):
ticket = request.COOKIES.get('ticket')
# if ticket existed
if ticket:
user_ticket = UserTicket.objects.filter(ticket=ticket).first()
if user_ticket:
return func(request)
else:
return HttpResponseRedirect(reverse('users:login'))
# if not existed
else:
return HttpResponseRedirect(reverse('users:login'))
return check
@is_login
def index(request):
if request.method == 'GET':
return render(request, 'index.html')
方法三:
使用中间件(middleware)
在utils目录下新建UserAuthMiddleware.py文件
在此文件中编写功能代码
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.utils.deprecation import MiddlewareMixin
from users.models import UserTicket
class UserMiddleware(MiddlewareMixin):
# rebuild process_request
@staticmethod
def process_request(request):
# get ticket
ticket = request.COOKIES.get('ticket')
# set urls which need no middleware
not_login_path = ['/users/login/', '/users/register/']
path = request.path
# check url
for n_path in not_login_path:
# which need no middleware
if path == n_path:
return
# no ticket,go to login.html
if not ticket:
return HttpResponseRedirect(reverse('users:login'))
# get user by ticket
user_ticket = UserTicket.objects.filter(ticket=ticket).first()
# check user
if not user_ticket:
# no such user,go to login.html
return HttpResponseRedirect(reverse('users:login'))
# set global user
request.user = user_ticket.user
# middleware ends,return
return None
校验
a)在视图函数中判断ticket是否为空,是否能在服务端中找到对应的user对象
b)使用闭包--->装饰器
外部内函数中内嵌函数,内嵌函数调用外部函数的参数,外部函数返回内部函数
c)中间件,重构process_ request()方法, 实现的功能和定义闭包的功能一样
302重定向
全局user, request. user默认为AnnoyMousUser