Python

Sessions on Google AppEngine for Python

In PHP world, creating sessions is so easy when using built ins. To customize, secure and make it fast, you have to create a whole new architecture to do that. In my experience with Google AppEngine, your only choice is the latter. I’ve implemented sessions via Cookie and Memcache.

Cookie + Memcache = Session

To create a very straightforward session in my Google AppEngine site, I used the combination of Cookie and memcache. Cookie will hold the session identifier and Memcache will hold the session data. I’ve put that methods on my base handler on a webapp2 based site.

Below is the quick and dirty code.

import os
import webapp2
import logging
import datetime

import dclab
import config
from google.appengine.api import memcache

class WebHandler(webapp2.RequestHandler):
    '''Base handler for site'''

    def __init__(self, request, response):
        self.initialize(request, response)
        self.template_params = get_template_params()
        self.session_identifier = 'gaesessid'
        self.session_id = None
        self.init_session()

    def init_session(self):
        session_id = self.request.cookies.get(self.session_identifier)
        if not session_id:
            session_id = dclab.generate_uuid()
            self.response.headers.add_header('Set-Cookie', '%s=%s; path=/' % (self.session_identifier, session_id))

        self.session_id = session_id

    def set_session_var(self, name, value):
        memkey = '%s-%s' % (self.session_id, name)
        memcache.set(memkey, value, 86400)

    def get_session_var(self, name):
        memkey = '%s-%s' % (self.session_id, name)
        return memcache.get(memkey)

    ... other methods here

init_session() – initializes the session. If the session does not yet exists, it creates a unique ID as the session identifier then store it on a cookie. If session already exists, it will fetch the session identifier from the cookie and store the session ID on the request handler object. The cookie is a session cookie and will expire when the browser is closed.

set_session_var() – sets a value into Memcache. The key is composed of the session ID and the session variable name, therefore it will prevent name collisions between users. It stores the value for 24 hours.

get_session_var() – retrieves value from Memcache. The key is composed of the session ID and the session variable name.

Usage

Usage is very simple. We just call the getter and setter methods like below:

# Set
token = dclab.generate_uuid()
self.set_session_var('token', token)

# Get
session_token = self.get_session_var('token')

Enjoy and share.

Leave a reply

Your email address will not be published. Required fields are marked *