python 为匿名django用户创建会话
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 为匿名django用户创建会话相关的知识,希望对你有一定的参考价值。
MIDDLEWARE_CLASSES = [
'django.contrib.sessions.middleware.SessionMiddleware',
# ...
]
ANONYMOUS_SESSION_PROCESS_FUNCTION = 'apps.common.middleware.process_anonymous_session'
# -*- coding: utf-8 -*
from __future__ import unicode_literals
import logging
from django.conf import settings
from importlib import import_module
engine = import_module(settings.SESSION_ENGINE)
SessionStore = engine.SessionStore
logger = logging.getLogger('django.request')
class AnonymousSessionMiddleware(object):
def process_request(self, request):
# type: (request) -> None
if not request.user.is_authenticated() and not request.session.session_key:
request.session = SessionStore()
request.session.create()
function_name = settings.get('ANONYMOUS_SESSION_PROCESS_FUNCTION')
if function_name:
msg = None
try:
function = __import__(function_name)
if callable(function):
function()
else:
msg = '"{}" is not callable'.format(function_name)
logger.warn(msg)
except ImportError:
msg = 'Can not import "{}"'.format(function_name)
logger.warn(msg)
except Exception as e:
msg = 'Error at processing Anonymous request'
logger.warn(msg, exc_info=True)
def process_anonymous_session(request):
# type: (request) -> None
pass
以上是关于python 为匿名django用户创建会话的主要内容,如果未能解决你的问题,请参考以下文章
FastAPI 中的会话
创建临时用户帐户 - Django
Axios 不存储 Django 会话 cookie
django 会话密钥在身份验证时更改
不要为匿名用户启动会话
我如何通过 ip 为匿名用户计算 django 中的视频观看次数