我想要有2个会话,一个用于我的应用程序(myapp.com),另一个用于管理员(myapp.com/admin)。有了这个,我可以访问我的Web客户端的不同选项卡,而无需在每次我想使用其中一个时登录。这很刺激。
我已经创建了一个新的会话中间件来控制它。
import time
from importlib import import_module
from django.conf import settings
from django.contrib.sessions.backends.base import UpdateError
from django.core.exceptions import SuspiciousOperation
from django.utils.cache import patch_vary_headers
from django.utils.deprecation import MiddlewareMixin
from django.utils.http import http_date
class AdminCookieSessionMiddleware(MiddlewareMixin):
def __init__(self, get_response=None):
self.get_response = get_response
engine = import_module(settings.SESSION_ENGINE)
self.SessionStore = engine.SessionStore
def cookie_name(self, request):
parts = request.path.split('/')
if len(parts) > 1 and parts[1].startswith('admin'):
return settings.ADMIN_SESSION_COOKIE_NAME
return settings.SESSION_COOKIE_NAME
def cookie_path(self, request):
parts = request.path.split('/')
if len(parts) > 1 and parts[1].startswith('admin'):
return settings.ADMIN_SESSION_COOKIE_PATH
return settings.SESSION_COOKIE_PATH
def process_request(self, request):
session_key = request.COOKIES.get(self.cookie_name(request))
request.session = self.SessionStore(session_key)
def process_response(self, request, response):
"""
If request.session was modified, or if the configuration is to save the
session every time, save the changes and set a session cookie or delete
the session cookie if the session has been emptied.
"""
try:
accessed = request.session.accessed
modified = request.session.modified
empty = request.session.is_empty()
except AttributeError:
pass
else:
# First check if we need to delete this cookie.
# The session should be deleted only if the session is entirely empty
if settings.SESSION_COOKIE_NAME in request.COOKIES and empty:
response.delete_cookie(
settings.SESSION_COOKIE_NAME,
path=settings.SESSION_COOKIE_PATH,
domain=settings.SESSION_COOKIE_DOMAIN,
)
else:
if accessed:
patch_vary_headers(response, ('Cookie',))
if (modified or settings.SESSION_SAVE_EVERY_REQUEST) and not empty:
if request.session.get_expire_at_browser_close():
max_age = None
expires = None
else:
max_age = request.session.get_expiry_age()
expires_time = time.time() + max_age
expires = http_date(expires_time)
# Save the session data and refresh the client cookie.
# Skip session save for 500 responses, refs #3881.
if response.status_code != 500:
try:
request.session.save()
except UpdateError:
raise SuspiciousOperation(
"The request's session was deleted before the "
"request completed. The user may have logged "
"out in a concurrent request, for example."
)
response.set_cookie(
self.cookie_name(request),
request.session.session_key, max_age=max_age,
expires=expires, domain=settings.SESSION_COOKIE_DOMAIN,
path=settings.SESSION_COOKIE_PATH,
secure=settings.SESSION_COOKIE_SECURE or None,
httponly=settings.SESSION_COOKIE_HTTPONLY or None,
)
return response
在我的设置文件中:
SESSION_COOKIE_NAME='usersessionid'
ADMIN_SESSION_COOKIE_NAME='adminsessionid'
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'core.utils.middleware.AdminCookieSessionMiddleware'
]
但是,我还有一个问题,即如果登录其中一个应用程序,我会自动退出另一个。
我正在追踪会话密钥,有时两个coockies都是一样的。这可以吗?如果没有,问题应该是什么?
答案 0 :(得分:0)
好的,我可以解决它,因此我发布了答案,所以我可以帮助某人尝试这样做。我从django SessionMiddleware复制代码并添加了一个cookie_name函数。在里面我创造了应该满足我需求的逻辑。 请务必将settings.SESSION_COOKIE_NAME替换为cookie_name。
import time
from importlib import import_module
from django.conf import settings
from django.contrib.sessions.backends.base import UpdateError
from django.core.exceptions import SuspiciousOperation
from django.utils.cache import patch_vary_headers
from django.utils.deprecation import MiddlewareMixin
from django.utils.http import http_date
class MySessionMiddleware(MiddlewareMixin):
def __init__(self, get_response=None):
self.get_response = get_response
engine = import_module(settings.SESSION_ENGINE)
self.SessionStore = engine.SessionStore
def cookie_name(self, request):
parts = request.path.split('/')
if settings.DEBUG:
if len(parts)>1 and parts[1].startswith('admin'):
return settings.ADMIN_SESSION_COOKIE_NAME
else:
if len(parts)>2 and parts[2].startswith('admin'):
return settings.ADMIN_SESSION_COOKIE_NAME
return settings.SESSION_COOKIE_NAME
def process_request(self, request):
session_key = request.COOKIES.get(self.cookie_name(request))
request.session = self.SessionStore(session_key)
def process_response(self, request, response):
"""
If request.session was modified, or if the configuration is to save the
session every time, save the changes and set a session cookie or delete
the session cookie if the session has been emptied.
"""
try:
accessed = request.session.accessed
modified = request.session.modified
empty = request.session.is_empty()
except AttributeError:
pass
else:
# First check if we need to delete this cookie.
# The session should be deleted only if the session is entirely empty
cookie_name = self.cookie_name(request)
if cookie_name in request.COOKIES and empty:
response.delete_cookie(
cookie_name,
path=settings.SESSION_COOKIE_PATH,
domain=settings.SESSION_COOKIE_DOMAIN,
)
else:
if accessed:
patch_vary_headers(response, ('Cookie',))
if (modified or settings.SESSION_SAVE_EVERY_REQUEST) and not empty:
if request.session.get_expire_at_browser_close():
max_age = None
expires = None
else:
max_age = request.session.get_expiry_age()
expires_time = time.time() + max_age
expires = http_date(expires_time)
# Save the session data and refresh the client cookie.
# Skip session save for 500 responses, refs #3881.
if response.status_code != 500:
try:
request.session.save()
except UpdateError:
raise SuspiciousOperation(
"The request's session was deleted before the "
"request completed. The user may have logged "
"out in a concurrent request, for example."
)
response.set_cookie(
cookie_name,
request.session.session_key, max_age=max_age,
expires=expires, domain=settings.SESSION_COOKIE_DOMAIN,
path=settings.SESSION_COOKIE_PATH,
secure=settings.SESSION_COOKIE_SECURE or None,
httponly=settings.SESSION_COOKIE_HTTPONLY or None,
)
return response
这非常重要:在设置中,在MIDDELWARE列表中,您必须添加它,但默认情况下也会删除SessionMiddleware。将其插入正常SessionMiddleware所在的相同位置。我们的想法是将它放在&#d; django.contrib.auth.middleware.AuthenticationMiddleware'之前,否则,您将收到错误。
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
#'django.contrib.sessions.middleware.SessionMiddleware',
'core.utils.middleware.MySessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]