Cookie
本质上:保存在用户浏览器上键值对。
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)