Bob
Bob

Reputation: 1237

django session outside of views

First off, before I want to get to the question, I want to say that if there is a more appropriate way to accomplish this, please let me know, since I'll probably be able to use that.

Ok, so I in my application, I need to add a REST API to allow a user to login, change a few things, and logout without needing to use a browser. I figured that I would have the api_login view I wrote would return their session_key and then make then pass the session key back in for each request. For example then

def login(request):
    ... all the django auth code I have
    # login adds the information to the request right?
    login (request, user)
    return simplejson.dumps({'key': request.session.session_key})

The problem I face is try later to use the session_key as follows, but this fails strangely

key = request.GET['key']
my_session = SessionStore(session_key=key)
my_session.session_key == key
>>> True
my_session.values()
>>> []
my_session.session_key == key
>>> False

So as you can see, I retrieve the SessionStore object from the database with the proper key. But then when I try to retrieve any of the values from it, it returns empty and the even changes the underlying key in it. Any advice on this is appreciated.

Upvotes: 2

Views: 3301

Answers (1)

Mike Shultz
Mike Shultz

Reputation: 1418

It appears Django either needs to know the session key, or has to generate it itself. My guess is either you're feeding it a random key or one it knows nothing about(because it wasn't saved). Your example works in my shell exactly the same way. Now here's my example:

>>> from django.contrib.sessions.backends.db import SessionStore
>>> key = 'asdf1234'
>>> my_session = SessionStore(session_key=key)
>>> my_session.session_key == key
True
>>> my_session['foo'] = 'bar'
>>> my_session.values()
['bar']
>>> my_session.session_key == key
False
>>> my_session.session_key
'358d6515b129631d89249687790adc49'
>>> my_session.save()

Then coming back:

>>> from django.contrib.sessions.backends.db import SessionStore
>>> my_session = SessionStore(session_key='358d6515b129631d89249687790adc49')
>>> my_session.values()
['bar']

So just let it do its thing and don't forget to save the session.

Upvotes: 4

Related Questions