kakakakakakakk
kakakakakakakk

Reputation: 519

django session key during session

I am looking for the session key that should be the same from the time when the user logs in until he logs out. I am communicating with another api that requires such key. I tried using csrf token but this one is different per request. Also, I have tried using session storage and again it is different one. I see that in the django_sessions there is a session_key that is created during the login, but I dont know how to assosiate it with a user, it has only session_key, session_data and the expire date.

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})

Upvotes: 0

Views: 1317

Answers (1)

user9304280
user9304280

Reputation:

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()

https://stackoverflow.com/a/5131421/9304280

Upvotes: 3

Related Questions