Cookie

Cookie

本质上:保存在用户浏览器上键值对。

image-20230716154707393

1 使用

from django.urls import path
from django.shortcuts import HttpResponse


def x1(request):
    # 包含:响应体、响应头、状态码等信息
    obj = HttpResponse("x1", status=201, reason="OK")
    # 设置响应头
    obj['name'] = "wupeiqi"

    # 设置cookie
    # import datetime
    # ctime = datetime.datetime.now() + datetime.timedelta(seconds=10)
    
    obj.set_cookie("v3", "root", max_age=10, path="/")
    obj.set_cookie("v2", "hello")
    obj.set_signed_cookie("info", "xiaoguang")  # 签名
    return obj


def x2(request):
    print(request.COOKIES)
    xx = request.get_signed_cookie("info")  # 用户不能自己修改cookie的内容
    print(xx)
    # print(request.COOKIES.get('v1'))
    # print(request.COOKIES.get('v2'))
    return HttpResponse("x2")


urlpatterns = [
    path('x1/', x1, name='x1'),
    path('x2/', x2, name='x2'),
]

2 源码

  • HttpResponse,包裹

    # 包含:响应体、响应头、状态码等信息
    obj = HttpResponse("x1", status=201, reason="OK")
    
    # 设置响应头
    obj['name'] = "wupeiqi"
    
    # 设置cookie
    # import datetime
    # ctime = datetime.datetime.now() + datetime.timedelta(seconds=10)
    
    obj.set_cookie("v3", "root", max_age=10, path="/")
    obj.set_cookie("v2", "hello")
    
    obj.set_signed_cookie("info", "xiaoguang")  # 签名
    return obj
    
  • WSGIRequest

    class WSGIHandler(base.BaseHandler):
        request_class = WSGIRequest
    
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.load_middleware()
    
        def __call__(self, environ, start_response):
            set_script_prefix(get_script_name(environ))
            signals.request_started.send(sender=self.__class__, environ=environ)
    
            request = self.request_class(environ)
    
    class HttpRequest:
        def get_signed_cookie(self, key, default=RAISE_ERROR, salt="", max_age=None):
            cookie_value = self.COOKIES[key]
            value = signing.get_cookie_signer(salt=key + salt).unsign(cookie_value, max_age=max_age)
    		return value
    
    class WSGIRequest(HttpRequest):
        def __init__(self, environ):
            self.environ = environ
            ...
            
        @cached_property
        def COOKIES(self):
            raw_cookie = get_str_from_wsgi(self.environ, "HTTP_COOKIE", "")
            return parse_cookie(raw_cookie)
    

本文作者:Sherwin

本文链接:https://www.cnblogs.com/sherwin1995/p/18410529

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   Sherwin_szw  阅读(8)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起
  1. 1 404 not found REOL
404 not found - REOL
00:00 / 00:00
An audio error has occurred.