当用户通过认证时,set_Cookie(key, value)
request.Cookie.get(key) 如果key不为空,就说明验证通过,否者重新跳转回login登录页面
对于URL
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^tp1/', views.tp1),
url(r'^user_list', views.user_list),
url(r'^login', views.login),
url(r'^Order/', views.Order.as_view()),
url(r'^index/', views.index)
]
对于views文件
user = {'name':'dacengzi', 'password':123}
def login(request):
if request.method == 'GET': #如果进来的方式是GET,直接跳转
return render(request, 'login.html')
elif request.method == 'POST': #如果是POST,说明用户已经上传
username = request.POST.get('username') #获取用户名
password = int(request.POST.get('password')) #获取密码
current_time = datetime.datetime.utcnow() #当前时间
current_time = current_time + datetime.timedelta(seconds=5) #当前时间推迟5秒 if username == user['name'] and password == user['password']: #如果用户名和密码匹配
req = redirect('/index/') req.set_cookie('correct', username, expires=current_time) #设置Cookie标志位
return req
else:
return render(request, 'login.html')
def auth(func):
def inner(request, *args, **kwargs):
answer = request.COOKIES.get('correct') #接收验证所得的标志位
if not answer: #如果没有收到重新跳转回登录界面
return render(request, 'login.html')
else: # 如果有就执行Order文件
return func(request, *args, **kwargs)
return inner
from django.utils.decorators import method_decorator
from django import views
@method_decorator(auth, name='dispatch') #给dispatch加装饰器,程序一进来就进行验证
class Order(views.View):
def get(self, request):
u = request.COOKIES.get('correct') #获取u,进行传递
return render(request, 'index.html', {'u': u}) def index(request):
return render(request, 'index.html')
对于login文件
<!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">
<input type="text" name="password">
<input type="submit" value="提交">
</form>
</body>
</html>