会话期间的 django 会话密钥

django session key during session

我正在寻找从用户登录到注销期间应该相同的会话密钥。我正在与另一个需要此类密钥的 api 通信。我尝试使用 csrf 令牌,但每个请求都不同。另外,我尝试过使用会话存储,但它又是不同的。我看到在 django_sessions 中有一个在登录期间创建的 session_key,但我不知道如何将它与用户关联,它只有 session_key、session_data 和到期日期。

def user_login(request):
    if request.method == 'POST':
        response = None
        form = LoginForm()
        username = request.POST.get("username")
        password = request.POST.get("password")
        cookie = request.COOKIES['csrftoken']
        user = authenticate(username=username, password=password)
        # logger.info(f"Session key [Login] --> {request.session}")
        # logger.info(f"Session key [Login] --> {request.session.session_key}")
        # request.session.create()
        # logger.info(f"Session key [Login] --> {request.session.session_key}")
        if user is not None:
            logger.info(f"Cookie [Login] --> {cookie}")
            response = loginApi(
                username, password, 'demo', cookie)
            if response["status"] == 200:
                login(request, user)
                logger.info("User logged in")
                return redirect('home')
            else:
                logger.info(f"Request Response [Log in] --> {response}")
        else:
            logger.error(f"User failed [Log in] --> {response.text}")
    else:
        form = LoginForm()

    return render(request, 'users/login.html', {'form': form})

request.session is a SessionStore object with a unique session_key.

The session_key is created as soon as the attribute is accessed. But the session object itself is only saved to the database after the view has been processed (in the process_response method of the session middleware) by calling the save method of the SessionStore object.

It's not really documented, but looking at the source code I guess you are supposed to create a new session object like this:

if not request.session.exists(request.session.session_key):
    request.session.create()