Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GAE webapp2 session: the correct process of creating and checking sessions

I tried to implement GAE's webapp2 session, but there seems very little documentation about it. According to http://webapp-improved.appspot.com/api/webapp2_extras/sessions.html, my steps are as follows:

1.Configure and add config to the main application:

config = {}
config['webapp2_extras.sessions'] = {
    'secret_key': 'my_secret_key',
}
app = webapp2.WSGIApplication([...], config=config)

2.Create session in the login handler

# Delete existent session
  --> not mention in the tutorial
# member is found    
self.session_store = sessions.get_store(request=handler.request)
self.session['account'] = member.account

3.Check if a session exists at various locations in my program

if self.session['account']:
    # Session exists

4.Delete session when user logs out

--> not mentioned in the tutorial

My questions:

  1. I got error message " ... object has no attribute 'session'" during the session creation process (Step 2)

  2. How do I delete a session in steps 2 and 4?

  3. Is the overall session management process correct?

Thanks.

like image 899
Randy Tang Avatar asked Dec 29 '12 01:12

Randy Tang


Video Answer


1 Answers

Here is an example of the handler and how to use webapp2 extra sessions

main.py with the BaseHandler and a MainHandler

import webapp2
from webapp2_extras import sessions

class BaseHandler(webapp2.RequestHandler):              # taken from the webapp2 extrta session example
    def dispatch(self):                                 # override dispatch
        # Get a session store for this request.
        self.session_store = sessions.get_store(request=self.request)

        try:
            # Dispatch the request.
            webapp2.RequestHandler.dispatch(self)       # dispatch the main handler
        finally:
            # Save all sessions.
            self.session_store.save_sessions(self.response)

    @webapp2.cached_property
    def session(self):
        # Returns a session using the default cookie key.
        return self.session_store.get_session()

class YourMainHandler(BaseHandler):

    def get(self):

        ....
        self.session['foo'] = 'bar'


    def post(self):


        foo = self.session.get('foo')

And if you have a seperate login.py :

.... other imports
import main

class Login(main.BaseHandler):

    def get(self):

        ....
        self.session['foo'] = 'bar'


    def post(self):


        foo = self.session.get('foo')
like image 153
voscausa Avatar answered Oct 25 '22 02:10

voscausa