Session
Session的使用一般依赖于Cookie,将一些数据不再发送值浏览器,而是保存的后端的服务器上。
1 使用
-
Session到底要存储到哪里?默认数据库。
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', # 'django.contrib.sessions', # sessions功能的APP django_session 'django.contrib.messages', 'django.contrib.staticfiles', ]
MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', # process_request/process_response 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', # "utils.md.KeLaMiddleware", ]
############ # SESSIONS # ############ # Session存储在哪里? SESSION_ENGINE = "django.contrib.sessions.backends.db" # 如果存储到文件中,文件的路径。 SESSION_ENGINE = "django.contrib.sessions.backends.file" SESSION_FILE_PATH = None # 存储到缓存 SESSION_ENGINE = "django.contrib.sessions.backends.cache" SESSION_CACHE_ALIAS = "default" # 存储到缓存 + 数据库 SESSION_ENGINE = "django.contrib.sessions.backends.cache_db" SESSION_CACHE_ALIAS = "default" # 存储到cookie SESSION_ENGINE = "django.contrib.sessions.backends.signed_cookies" # class to serialize session data SESSION_SERIALIZER = "django.contrib.sessions.serializers.JSONSerializer" # ------------------------------- # Cookie name. This can be whatever you want. SESSION_COOKIE_NAME = "sessionid" # Age of cookie, in seconds (default: 2 weeks). SESSION_COOKIE_AGE = 60 * 60 * 24 * 7 * 2 # A string like "example.com", or None for standard domain cookie. SESSION_COOKIE_DOMAIN = None # Whether the session cookie should be secure (https:// only). SESSION_COOKIE_SECURE = False # The path of the session cookie. SESSION_COOKIE_PATH = "/" # Whether to use the HttpOnly flag. SESSION_COOKIE_HTTPONLY = True # Whether to set the flag restricting cookie leaks on cross-site requests. # This can be 'Lax', 'Strict', 'None', or False to disable the flag. SESSION_COOKIE_SAMESITE = "Lax" # Whether to save the session data on every request. SESSION_SAVE_EVERY_REQUEST = False # Whether a user's session cookie expires when the web browser is closed. SESSION_EXPIRE_AT_BROWSER_CLOSE = False
注意:如果是非数据库,可以主调用app的注册代码部分。
-
请求=登录,生成Session、Cookie。
-
再次请求,默认携带cookie,根据Cookie中的凭证,去找到Session中原本存储的数据。
request.session['id'] = 999 request.session['id'] = 88 request.session.get("id") # del request.session['id'] # request.session.clear()
from django.urls import path from django.shortcuts import HttpResponse def x1(request): request.session['id'] = 999 request.session['name'] = 'wupeiqi' request.session['age'] = '25' return HttpResponse("x1") def x2(request): print(request.session.get("id")) print(request.session.get("name")) print(request.session.get("age")) return HttpResponse("x2") urlpatterns = [ path('x1/', x1, name='x1'), path('x2/', x2, name='x2'), ]
2 源码
1.引擎配置
-
数据库引擎
SESSION_ENGINE = "django.contrib.sessions.backends.db"
INSTALLED_APPS = [ 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ]
>>>python manage.py makemigrations >>>python manage.py migrate
-
文件
# 如果存储到文件中,文件的路径。 SESSION_ENGINE = "django.contrib.sessions.backends.file" SESSION_FILE_PATH = None
INSTALLED_APPS = [ #'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ]
2.中间件
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware', # 必须设置
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
...
]
2.1 创建对象
在启动django程序时,会自动创建 SessionMiddlewared对象。
class MiddlewareMixin:
def __init__(self, get_response):
self.get_response = get_response
class SessionMiddleware(MiddlewareMixin):
def __init__(self, get_response):
super().__init__(get_response)
# "django.contrib.sessions.backends.db" "django.contrib.sessions.backends.file"
engine = import_module(settings.SESSION_ENGINE)
# db.SessionStore file.SessionStore
self.SessionStore = engine.SessionStore
2.2 请求到来 *
def process_request(self, request):
# 1.去Cookie中读取凭证 mid="123123123123"
session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME)
# 2.实例化
request.session = self.SessionStore(session_key)
def x1(request):
# request.session -> file.SessionStore() /
request.session['id'] = 999
request.session['name'] = 'wupeiqi' 类中的__setitem__
request.session['age'] = '25'
return HttpResponse("x1")
2.3 请求结束 *
...
标签:session,Session,sessions,request,django,SESSION,contrib
From: https://www.cnblogs.com/sherwin1995/p/18410535