django设置cookie

明瞳 2020-06-12

两个例子:

使用模板

  from django.shortcuts import render, HttpResponse
  from rest_framework.views import APIView

class Order(APIView):
    def get(self, request, *args, **kwargs):
        response= render(request,‘login.html‘)
        response.set_cookie(‘username‘,‘xiaoming‘)  # 设置cookie
        return response

    def post(self, request, *args, **kwargs):
        ret = request.COOKIES[‘username‘]  # 获取cookie
        return HttpResponse(ret)

不使用模板

from django.shortcuts import render, HttpResponse
from rest_framework.views import APIView

class Order(APIView):
    
    def GET(self, request, *args, **kwargs):
        response = HttpResponse("ok")
        response.set_cookie("username","xiaoming")  # 设置cookie
        return response

    def GET(self, request, *args, **kwargs):
        ret = request.COOKIES["username"]  # 获取cookie
        res = request.COOKIES.get("username")  # 获取cookie
        return Httpresponse("success")

Django中操作Cookie

获取Cookie

request.COOKIES[‘key‘]
request.get_signed_cookie(key, default=RAISE_ERROR, salt=‘‘, max_age=None)

参数:

  • default: 默认值
  • salt: 加密盐
  • max_age: 后台控制过期时间

设置Cookie

rep = HttpResponse(...)
rep = render(request, ...)

rep.set_cookie(key,value,...)
rep.set_signed_cookie(key,value,salt=‘加密盐‘,...)

参数:

  • key, 键
  • value=‘‘, 值
  • max_age=None, 超时时间
  • expires=None, 超时时间(IE requires expires, so set it if hasn‘t been already.)
  • path=‘/‘, Cookie生效的路径,/ 表示根路径,特殊的:根路径的cookie可以被任何url的页面访问
  • domain=None, Cookie生效的域名
  • secure=False, https传输
  • httponly=False 只能http协议传输,无法被JavaScript获取(不是绝对,底层抓包可以获取到也可以被覆盖)

删除Cookie

def logout(request):
    rep = redirect("/login/")
    rep.delete_cookie("user")  # 删除用户浏览器上之前设置的usercookie值
    return rep

 结束!

相关推荐

inspuryhq / 0评论 2020-07-28