如何在django中跟踪我自己的中间件中的用户会话?

时间:2021-10-26 20:35:23

Django's session middleware only assigns a session key when the session is first saved. How do I use the session key in my own middleware?

Django的会话中间件仅在首次保存会话时分配会话密钥。如何在我自己的中间件中使用会话密钥?

1 个解决方案

#1


0  

The first request of a new session does not have a session key. In order to track user sessions from the very first request, use your own custom identifier, something like this:

新会话的第一个请求没有会话密钥。要从第一个请求跟踪用户会话,请使用您自己的自定义标识符,如下所示:

import base32_crockford
import uuid
...
MY_SESSION_KEY='my_custom_session_key'
...
 def process_request(self, request):
        if MY_SESSION_KEY not in request.session:
            if request.session.session_key is None:
                my_key = base32_crockford.encode(uuid.uuid4()).lower()
                request.session[MY_SESSION_KEY] = my_key
            else:
                request.session[MY_SESSION_KEY] = request.session.session_key

        session_instance = request.session[MY_SESSION_KEY]

This code will use the existing session key if it exists, or create a new random key (I encode with base32 for easier copy-pasting of the values). You can use the string value of the UUID directly if you prefer.

此代码将使用现有的会话密钥(如果存在),或创建新的随机密钥(我使用base32编码以便更容易地复制粘贴值)。如果您愿意,可以直接使用UUID的字符串值。

#1


0  

The first request of a new session does not have a session key. In order to track user sessions from the very first request, use your own custom identifier, something like this:

新会话的第一个请求没有会话密钥。要从第一个请求跟踪用户会话,请使用您自己的自定义标识符,如下所示:

import base32_crockford
import uuid
...
MY_SESSION_KEY='my_custom_session_key'
...
 def process_request(self, request):
        if MY_SESSION_KEY not in request.session:
            if request.session.session_key is None:
                my_key = base32_crockford.encode(uuid.uuid4()).lower()
                request.session[MY_SESSION_KEY] = my_key
            else:
                request.session[MY_SESSION_KEY] = request.session.session_key

        session_instance = request.session[MY_SESSION_KEY]

This code will use the existing session key if it exists, or create a new random key (I encode with base32 for easier copy-pasting of the values). You can use the string value of the UUID directly if you prefer.

此代码将使用现有的会话密钥(如果存在),或创建新的随机密钥(我使用base32编码以便更容易地复制粘贴值)。如果您愿意,可以直接使用UUID的字符串值。