功能 :session & cookie

2. 自己设置cookie和session

2.1

  1. 重新写url,增加一个用户注册界面


  2. 建立用户表
class User(models.Model):
    username = models.CharField(max_length=40)
    password = models.CharField(max_length=255)
    create_time = models.DateTimeField(auto_now_add=True)
    session_id = models.CharField(max_length=30, null=True)
    out_time = models.DateTimeField(null=True)

    class Meta:
        db_table = 'user'
  1. 用户注册函数

def my_register(request):

    if request.method == 'GET':
        return render(request,'backweb/my_register.html')

    if request.method == 'POST':
        username = request.POST.get('username')
        password1 = request.POST.get('password1')
        password2 = request.POST.get('password2')

        # 验证用户是否存在
        user = User.objects.filter(username=username).exists()
        if user:
            error = '用户名已被注册'
            return  render(request,'backweb/my_register.html', {'error':error})
        else:
            if password1 == password2:
                User.objects.create(username=username, password=password1)
                return HttpResponseRedirect(reverse('backweb:my_login'))
            else:
                error = '两次密码不一致'
                return render(request,'backweb/my_register.html', {'error':error})

  1. 登录函数,并创建cookie
    登录的时候,设置cookie中的随机字符串session_id *
    向服务端保存这个字符串
def my_login(request):
    if request.method == 'GET':
        return render(request, 'backweb/login.html')

    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')

        user = User.objects.filter(username=username, password=password).first()
        if user:
            # 账号密码正确
            # 第一步,cookie中设值
            res = HttpResponseRedirect(reverse('backweb:index'))
            s = 'abcdefghijklmnopqrstuvwxyz1234567890'
            session_id = ''  # 工作中叫车票
            for i in range(20):
                session_id += random.choice(s)
            out_time = datetime.now() + timedelta(1)   # 过期时间,设置为1天
            res.set_cookie('session_id', session_id, expires=out_time)
             # 第二部,服务器存cookie中设的值
            user.session_id = session_id
            user.out_time = out_time
            user.save()
            return res
        else:
            error = '用户名或者密码错误'
            return render(request, 'backweb/login.html', {'error': error})

2.2中间键(有5个): 拦截,过滤请求:

  • 获取cookie中的随机字符串
  • 在服务端进行校验,半段cookie中的随机字符串是否在服务器中保存,并拿到相关的用户信息
  • 判断,如果拿不到用户的信息,则让用户跳转到登录
a. 建立中间键(扩展包-utils,导入相关模块)
image.png
b. settings.py配置,注意修改跳转路径
image.png
c. 中间键分类 :

process_request(self,request)
process_view(self, request, view_func, view_args, view_kwargs)
process_template_response(self,request,response)
process_exception(self, request, exception)
process_response(self, request, response)

你可能感兴趣的:(功能 :session & cookie)