让gae-sessions在App Engine中工作的问题,错误没有帮助

时间:2011-01-25 02:27:09

标签: python google-app-engine

我已经将gae-sessions安装到我的开发环境中,但它似乎没有存储任何东西。这是一个基本的例子:

session = get_current_session()
session.get('some_num', 3)

然后在其他一些功能......

session = get_current_session()
session['some_num'] = 4

这是我在控制台中遇到的错误:

KeyError: 'some_num'

不是一个非常有用的错误。我很确定我已按照说明书写了这封信,但也许有些东西我不见了?

修改

appengine_config.py

from gaesessions import SessionMiddleware
import os

def webapp_add_wsgi_middleware(app):
    app = SessionMiddleware(app, os.urandom(32))
    return app

违规代码

class Test(webapp.RequestHandler):
    def get(self):
        session = get_current_session()
        if session.is_active():
            # set session['some_num'] to whatever was in there or three, otherwise
            session['some_num'] = session.get('some_num', 3) 

            # later, session['some_num'] should exist and be equal to 3 ...
            assert session['some_num'] == 3

            # ... and is actually 'settable'
            session['some_num'] = 4
        else:
            self.response.out.write("Session is NOT active")

.is_active()不会返回true。

2 个答案:

答案 0 :(得分:2)

查看示例应用程序(here),似乎所有会话都处于非活动状态,并在第一次存储值时自动设置为活动状态。您应该只需使用session['foo'] = 'bar'将值存储到会话中,它就会自动激活会话。

另请注意,您不应该像这样生成cookie密钥。正如sample appengine_config.py中的文档所说:

# suggestion: generate your own random key using os.urandom(64)
# WARNING: Make sure you run os.urandom(64) OFFLINE and copy/paste the output to
# this file.  If you use os.urandom() to *dynamically* generate your key at
# runtime then any existing sessions will become junk every time you start,
# deploy, or update your app!

答案 1 :(得分:0)

在您的代码中(原样),您不首先将some_num添加到会话字典中。尝试:

from gaesessions import get_current_session
session = get_current_session()
if session.is_active():
    # set session['some_num'] to whatever was in there or three, otherwise
    session['some_num'] = session.get('some_num', 3) 
...

# later, session['some_num'] should exist and be equal to 3 ...
assert session['some_num'] == 3

# ... and is actually 'settable'
session['some_num'] = 4