cookie+session(验证登录)

设置session过期时间需要用到的配置

SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'

视图函数

from datetime import datetime, timedelta

from django.contrib.auth.hashers import check_password
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse

from users.models import Users
from utils.functions import is_login


def login(request):
    if request.method == 'GET':
        return render(request, 'login.html')

    if request.method == 'POST':
        # 使用Cookie+Session形式实现登录
        username = request.POST.get('username')
        password = request.POST.get('password')
        # all()校验参数,若列表中存在元素为空,则返回False
        if not all([username, password]):
            msg = '请填写完整的登录信息'
            return render(request, 'login.html', {'msg': msg})

        # 校验是否能通过username和password找到user对象
        user = Users.objects.filter(username=username).first()
        if user:
            # 校验密码
            if not check_password(password, user.password):
                msg = '密码错误'
                return render(request, 'login.html', {'msg': msg})
            else:
                # 向cookie中设置随机值,并存取至user_ticker中
                request.session['user_id'] = user.id

                # 设置session过期时间

                request.session.set_expiry(timedelta(days=1))

                return HttpResponseRedirect(reverse('users:index'))
        else:
            msg = '用户名不存在'
            return render(request, 'login.html', {'msg': msg})


@is_login
def index(request):
    if request.method == 'GET':
        user_id = request.session.get('user_id')
        return render(request, 'index.html')


@is_login
def logout(request):
    if request.method == 'GET':
        # 注销,删除session和cookie
        # request.session.flush()
        # 获取session_key并实现删除,删除服务端
        # session_key = request.session.session_key
        # request.session.delete(session_key)

        return HttpResponseRedirect(reverse('users:login'))

装饰器

from django.http import HttpResponseRedirect
from django.urls import reverse


def is_login(func):
    def check(request):
        try:
            # 获取session中已保存的user_id的值
            request.session['user_id']
        except:
            # 跳转到登录
            return HttpResponseRedirect(reverse('users:login'))
        return func(request)

    return check

去除settings中对csrf的注释

'django.middleware.csrf.CsrfViewMiddleware',

在前端FORM表单中加上{% csrf_token %}即可

你可能感兴趣的:(cookie+session(验证登录))