Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 707957
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T04:20:11+00:00 2026-05-14T04:20:11+00:00

Here is a very basic class for handling sessions on App Engine: Lightweight implementation

  • 0

Here is a very basic class for handling sessions on App Engine:

"""Lightweight implementation of cookie-based sessions for Google App Engine.

Classes:
Session

"""

import os
import random
import Cookie
from google.appengine.api import memcache

_COOKIE_NAME = 'app-sid'
_COOKIE_PATH = '/'
_SESSION_EXPIRE_TIME = 180 * 60


class Session(object):

    """Cookie-based session implementation using Memcached."""

    def __init__(self):
        self.sid = None
        self.key = None
        self.session = None
        cookie_str = os.environ.get('HTTP_COOKIE', '')
        self.cookie = Cookie.SimpleCookie()
        self.cookie.load(cookie_str)
        if self.cookie.get(_COOKIE_NAME):
            self.sid = self.cookie[_COOKIE_NAME].value
            self.key = 'session-' + self.sid
            self.session = memcache.get(self.key)
        if self.session:
            self._update_memcache()
        else:
            self.sid = str(random.random())[5:] + str(random.random())[5:]
            self.key = 'session-' + self.sid
            self.session = dict()
            memcache.add(self.key, self.session, _SESSION_EXPIRE_TIME)
            self.cookie[_COOKIE_NAME] = self.sid
            self.cookie[_COOKIE_NAME]['path'] = _COOKIE_PATH
            print self.cookie

    def __len__(self):
        return len(self.session)

    def __getitem__(self, key):
        if key in self.session:
            return self.session[key]
        raise KeyError(str(key))

    def __setitem__(self, key, value):
        self.session[key] = value
        self._update_memcache()

    def __delitem__(self, key):
        if key in self.session:
            del self.session[key]
            self._update_memcache()
            return None
        raise KeyError(str(key))

    def __contains__(self, item):
        try:
            i = self.__getitem__(item)
        except KeyError:
            return False
        return True

    def _update_memcache(self):
        memcache.replace(self.key, self.session, _SESSION_EXPIRE_TIME)

I would like some advices on how to improve the code for better security.

Note: In the production version it will also save a copy of the session in the datastore.

Note’: I know there are much more complete implementations available online though I would like to learn more about this subject so please don’t answer the question with “use that” or “use the other” library.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T04:20:11+00:00Added an answer on May 14, 2026 at 4:20 am

    Here is a suggestion for simplifying your implementation.

    You are creating a randomized temporary key that you use as the session’s key in the memcache. You note that you will be storing the session in the datastore as well (where it will have another key).

    Why not randomize the session’s datastore key, and then use that as the one and only key, for both the database and the memcache (if necessary)? Does this simplification introduce any new security issues?

    Here’s some code for creating a randomized datastore key for the Session model:

    # Get a random integer to use as the session's datastore ID.
    # (So it can be stored in a cookie without being 'guessable'.)
    random.seed();
    id = None;
    while None==id or Session.get_by_id( id ):
        id = random.randrange( sys.maxint );
    seshKey = db.Key.from_path( 'Session', id );    
    session = Session( key = seshKey );
    

    To get the ID from the session (i.e. to store in the cookie) use:

    sid = session.key().id();
    

    To retrieve the session instance after the ‘sid’ has been read from the cookie:

    session = Session.get_by_id( sid );
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 436k
  • Answers 436k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer No responses, so here's what experimentation showed. From our application,… May 15, 2026 at 3:48 pm
  • Editorial Team
    Editorial Team added an answer MCTS 70-511 is a combination of both WPF and WinForms.… May 15, 2026 at 3:48 pm
  • Editorial Team
    Editorial Team added an answer See the same problem: http://drupal.org/node/434394 May 15, 2026 at 3:48 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.