Web接口开发与自动化测试

django.contrib.auth

from django.contrib import auth
def login_action(request):
if request.method == 'POST':
username = request.POST.get('username','')
password = request.POST.get('password','')
     # 登陆认证,如果认证通过返回user,认证不通过返回None
user = auth.authenticate(username=username,password=password)
if user is not None:
      """
      Persist a user id and a backend in the request. This way a user doesn't
      have to reauthenticate on every request. Note that data set during
      the anonymous session is retained when the user logs in.
      """
            auth.login(request,user)
request.session['user'] = username
response = HttpResponseRedirect('/event_manage/')
# 设置cookie,3600为保持时间,默认为秒
# response.set_cookie('user', username, 3600)

return response
else:
return render(request, 'index.html', {'error':'账号或密码错误!'})


如果想要限制某个视图函数必须要登陆才能访问,只需在该函数前面加上@login_required即可
from django.contrib.auth.decorators import login_required

退出登陆
def logout(request):
auth.logout(request) # 退出登陆,清除浏览器的用户信息
return HttpResponseRedirect('/index/')
原文地址:https://www.cnblogs.com/Tester_Dolores/p/11888876.html