Totty.js
Totty.js

Reputation: 15831

How to get current session with only the SID?

How can I retrieve a session using only its session identifier (SID)? I'm using gae-sessions.

Update for response @David Underhill:

I've done what you suggested, but in debug mode I got this: Session: SID=None {} | but it has db_key populated with a string.

Here is my code:

upload.py

SID = self.request.get("SID")
if not SID:
return False

from app.models.user import User
user = User.get_current_user(SID)

user.py

def get_current_user(SID = None):
    if SID:
        session = Session(sid=SID)
    else:
        session = get_current_session()

    if session.has_key('account.logged'):
        return User.get(db.Key(session.get('user.key')))
    else:
        return False

and doesn't exists.

And this is my SID from my cookie:

"mMumLZOCq5knTg9edaSjLD+p8xsSohAQSS9vyqpgDso=1289155992_9c2c85c6931a7d133f7e1f0b9ae25502gAJ9cQB9cQEoVQ5hY2NvdW50LmxvZ2dlZHECiFUIdXNlci5rZXlxA1UjYWd0MGIzUjBlWE4zYjNKc1pISUxDeElFVlhObGNoaTNBUXdxBFULYWNjb3VudC5rZXlxBVUnYWd0MGIzUjBlWE4zYjNKc1pISU9DeElIUVdOamIzVnVkQmkyQVF3cQZVDWFjY291bnQuZW1haWxxB1UBdHEIdYZxCS4="

I take this from cookies, with JavaScript and Flex, then send it in a variable to Python.

Upvotes: 2

Views: 1584

Answers (1)

David Underhill
David Underhill

Reputation: 16243

To retrieve a session used only its SID, directly instantiate the Session class:

session = gaesessions.Session(sid="SID of the session you want")

If you want to retrieve a session using only its session ID, then that session must have been persisted to the datastore or memcache. By default, gae-sessions only stores small sessions in secure cookies which are much faster than either memcache or the datastore.

To force a particular session to be saved to the datastore, you can call save(persit_even_if_using_cookie=True) on the session object. This will force it to be stored to the datastore/memcache even if it normally would only be stored in a cookie. This is the best approach if you only need to occasionally access user sessions by SID alone.

If you need to frequently access sessions by SID, then you might be better off disabling the cookie-only mechanism by passing cookie_only_threshold=0 to the SessionMiddleware when you configure it - this will ensure that cookies are never used and that your sessions are always in the datastore.

These details and more are documented more thoroughly in the gae-sessions documentation.

Upvotes: 2

Related Questions