GAE webapp2会话:创建和检查会话的正确过程

时间:2012-12-29 01:59:25

标签: google-app-engine session webapp2

我试图实现GAE的webapp2会话,但似乎很少有关于它的文档。根据{{​​3}},我的步骤如下:

1.配置并添加配置到主应用程序:

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

2.在登录处理程序中创建会话

# 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.检查我的程序中不同位置是否存在会话

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

4.用户注销时删除会话

--> not mentioned in the tutorial

我的问题:

  1. 我在会话创建过程中收到错误消息“...对象没有属性'session'”(步骤2)

  2. 如何在步骤2和4中删除会话?

  3. 整个会话管理流程是否正确?

  4. 感谢。

3 个答案:

答案 0 :(得分:16)

以下是处理程序的示例以及如何使用webapp2额外会话

main.py与BaseHandler和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')

如果你有一个单独的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')

答案 1 :(得分:5)

这可能不是问题的直接答案,但这是我使用gaesessions而不是GAE的webapp2会话找到的解决方案,我想与大家分享。我们走了:

  1. 点击“下载ZIP”按钮,从https://github.com/dound/gae-sessions下载gaesessions。下载的文件是“gae-sessions-master.zip”。

  2. 解压缩文件(将创建目录“gae-sessions-master”),并将目录“gaessions”复制到应用程序的根目录(即“app.yaml”所在的位置)< / p>

  3. 在根目录中创建一个名为“appengine_config.py”的文件,其中包含以下内容(复制形式为https://github.com/dound/gae-sessions/tree/master/demo):

    from gaesessions import SessionMiddleware
    
    # Original comments deleted ... 
    # Create a random string for COOKIE_KDY and the string has to
    # be permanent. "os.urandom(64)" function may be used but do
    # not use it *dynamically*.
    # For me, I just randomly generate a string of length 64
    # and paste it here, such as the following:
    
    COOKIE_KEY = 'ppb52adekdhD25dqpbKu39dDKsd.....'
    
    def webapp_add_wsgi_middleware(app):
        from google.appengine.ext.appstats import recording
        app = SessionMiddleware(app, cookie_key=COOKIE_KEY)
        app = recording.appstats_wsgi_middleware(app)
        return app
    
  4. 用户登录时创建会话(变量帐户是用户的帐户):

    from gaesessions import get_current_session
    session = get_current_session()
    if session.is_active():
        session.terminate()
    # start a session for the user (old one was terminated)
    session['account'] = account
    
  5. 检查用户的会话是否存在,如果是,则返回用户的帐户:

    from gaesessions import get_current_session
    def checkSession():
        session = get_current_session()
        if session.is_active():
            return session['account']
        return False
    
  6. 用户退出时删除会话:

    def logout():
        session = get_current_session()
        if session.is_active():
            session.terminate()
    
  7. 最后,您可以创建一个cron作业来定期清理过期的会话:

  8. cron.yaml:

    - description: daily session cleanup
      url: /clean_up_sessions
      schedule: every day 3:00
      timezone: ... (Your time zone)
    

    功能:

    from gaesessions import delete_expired_sessions
    class clean_up_sessions(webapp2.RequestHandler):
        def get(self):
            while not delete_expired_sessions():
                pass
    

    希望这有帮助。

答案 2 :(得分:3)

RequestHandler覆盖dispatch中:     来自webapp2_extras导入会话

def dispatch(self):

    self.session_store = sessions.get_store(request=self.request)

    try:
        webapp2.RequestHandler.dispatch(self)
    finally:
        self.session_store.save_sessions(self.response)

并制作名为webapp2.cached_property的{​​{1}}:

session

如果要访问会话值,请执行@webapp2.cached_property def session(self): return self.session_store.get_session(backend="<whatever you want here>")

当用户登录时,您可以调用:

self.session[<key>]

将负责摆脱旧会话并为您创建新会话,或者:

 self.auth.get_user_by_password(auth_id, password, remember=True,
                                           save_session=True)

就注销而言,您需要调用的是:

self.auth.set_session(self.auth.store.user_to_dict(self.user), remember=True)