Google App Engine - Getting Sessions working with Python 2.7

后端 未结 1 1923
被撕碎了的回忆
被撕碎了的回忆 2020-12-08 06:05

First of all, I\'m brand new to GAE, so its possible I\'m doing this the wrong way - but I\'ve used PHP before and session was how I kept persistent data. I\'m using Python

相关标签:
1条回答
  • 2020-12-08 06:28

    Have you seen webapp2 sessions? It's all built in and you can get started right away.

    https://webapp2.readthedocs.io/en/latest/api/webapp2_extras/sessions.html

    This module provides a lightweight but flexible session support for webapp2. It has three built-in backends: secure cookies, memcache and datastore. New backends can be added extending CustomBackendSessionFactory. The session store can provide multiple sessions using different keys, even using different backends in the same request, through the method SessionStore.get_session(). By default it returns a session using the default key from configuration.

    import webapp2
    
    from webapp2_extras import sessions
    
    class BaseHandler(webapp2.RequestHandler):
        def dispatch(self):
            # Get a session store for this request.
            self.session_store = sessions.get_store(request=self.request)
    
            try:
                # Dispatch the request.
                webapp2.RequestHandler.dispatch(self)
            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()
    
    # To set a value:
    self.session['foo'] = 'bar'
    
    # To get a value:
    foo = self.session.get('foo')
    

    Then it's real easy to build a login system around this, seems you've already done it already. And you get to use the datastore and/or memcache with the webapp2 sessions, as preferred.

    0 讨论(0)
提交回复
热议问题