15

我试图实现 GAE 的 webapp2 会话,但是关于它的文档似乎很少。根据http://webapp-improved.appspot.com/api/webapp2_extras/sessions.html,我的步骤如下:

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. 我在会话创建过程中收到错误消息“...对象没有属性'会话'”(步骤 2)

  2. 如何删除第 2 步和第 4 步中的会话?

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

谢谢。

4

3 回答 3

16

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

带有 BaseHandler 和 MainHandler 的 main.py

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')
于 2012-12-29T15:17:19.723 回答
5

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

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

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

  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. 当用户登录时创建会话(变量account是用户的账户):

    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 作业来定期清理过期的会话:

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

希望这可以帮助。

于 2013-01-04T05:54:23.170 回答
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调用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)

至于注销,您只需要调用:

self.auth.unset_session()
于 2013-08-26T20:34:09.843 回答