1.Cookie本质是客户端浏览器上的一个文件
这里用Cookies实现简单的用户登录:
views.py:
def login(request): if request.method == "GET": return render(request, 'login.html') if request.method == "POST": u = request.POST.get('username') p = request.POST.get('pwd') dic = user_info.get(u) if not dic: return render(request, 'login.html') if dic['pwd'] == p: res = redirect('/index/') res.set_cookie('username111', u) #max_age设置失效时间(秒) return res else: return render(request, 'login.html') def index(request): v = request.COOKIES.get('username111') if not v: return redirect('/login/') return render(request, 'index.html', {'current_user': v})
index.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>欢迎{{ current_user }}登录</h1> </body> </html>
login.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/login/" method="POST"> <input type="text" name="username" placeholder="用户名"/> <input type="password" name="pwd" placeholder="密码"/> <input type="submit" value="登录"/> </form> </body> </html>
这样直接访问index不会成功,必须要登录后才可以访问,访问成功后页面显示当前的用户名。
cookie这里还可以设置参数,这里介绍一个常用的(这里的cookies只在五秒内有效):
import datetime current_date = datetime.datetime.utcnow() current_date = current_date + datetime.timedelta(seconds=5) res.set_cookie('username111', u, expires=current_date)
这里的Cookies是明文的,可以机密,比如这样(这里的salt是自己任意写的,但是要注意,设置和获取的盐要一致):
obj = HttpResponse('666') obj.set_signed_cookie('username', 'root', salt="jiageyan") request.get_signed_cookie('username', salt="jiageyan")
有时候需要多次用户认证,为了不重复写代码,可以加入用户认证装饰器:
FBV装饰器:
def auth(func): def inner(request, *args, **kwargs): v = request.COOKIES.get('username111') if not v: return redirect('/login/') return func(request, *args, **kwargs) return inner @auth def index(request): v = request.COOKIES.get('username111') return render(request, 'index.html', {'current_user': v})
CBV装饰器:
def auth(func): def inner(request, *args, **kwargs): v = request.COOKIES.get('username111') if not v: return redirect('/login/') return func(request, *args, **kwargs) return inner from django import views from django.utils.decorators import method_decorator @method_decorator(auth, name='dispatch') class Order(views.View): #装饰类的原理相当于下边这三行代码 #@method_decorator(auth) #def dispatch(self, request, *args, **kwargs): # return super(Order, self).dispatch(self, request, *args, **kwargs) def get(self, request): v = request.COOKIES.get('username111') return render(request, 'index.html', {'current_user': v}) def post(self, request): v = request.COOKIES.get('username111') return render(request, 'index.html', {'current_user': v})