Google App Engine - Getting Sessions working with Python 2.7

我与影子孤独终老i 提交于 2019-11-28 05:07:32
Paul Collingwood

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!