错误序列化与webapp2_extras的GAE会话

时间:2015-08-29 18:18:14

标签: python-2.7 google-app-engine webapp2

我不是App Engine的新手,但我刚开始使用Python堆栈。我使用webapp2和Cygwin使用自己的Python。我正在尝试实现自定义身份验证,依赖会话。我正在关注使用webapp2-extras模块启用会话的大量示例。我有以下相关代码:

import webapp2

from webapp2_extras import sessions

class BaseHandler(webapp2.RequestHandler):
    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
    def session(self):
        return self.session_store.get_session(self.response, backend='datastore')

class CounterHandler(BaseHandler):
    def get(self):
        cnt_key = 'cnt'
        if cnt_key in self.session:
            cnt = int(self.session[cnt_key])
        else:
            cnt = 0
        cnt += 1
        self.session[cnt_key] = str(cnt)

        self.response.headers['Content-Type'] = 'text/plain'
        self.response.write("Hello, world!")

以下堆栈跟踪失败:

Traceback (most recent call last):
  File "/cygdrive/c/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1535, in __call__
    rv = self.handle_exception(request, response, e)
  File "/cygdrive/c/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1529, in __call__
    rv = self.router.dispatch(request, response)
  File "/cygdrive/c/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1278, in default_dispatcher
    return route.handler_adapter(request, response)
  File "/cygdrive/c/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1102, in __call__
    return handler.dispatch()
  File "/cygdrive/c/Documents and Settings/dev/My Documents/proj/easytime_gae/src/handlers.py", line 11, in dispatch
    self.session_store.save_sessions(self.response)
  File "/cygdrive/c/google_appengine/lib/webapp2-2.5.2/webapp2_extras/sessions.py", line 420, in save_sessions
    session.save_session(response)
  File "/cygdrive/c/google_appengine/lib/webapp2-2.5.2/webapp2_extras/appengine/sessions_ndb.py", line 117, in save_session
    response, self.name, {'_sid': self.sid}, **self.session_args)
  File "/cygdrive/c/google_appengine/lib/webapp2-2.5.2/webapp2_extras/sessions.py", line 423, in save_secure_cookie
    value = self.serializer.serialize(name, value)
  File "/cygdrive/c/google_appengine/lib/webapp2-2.5.2/webapp2_extras/securecookie.py", line 48, in serialize
    signature = self._get_signature(name, value, timestamp)
  File "/cygdrive/c/google_appengine/lib/webapp2-2.5.2/webapp2_extras/securecookie.py", line 103, in _get_signature
    signature.update('|'.join(parts))
TypeError: sequence item 0: expected string, Response found

如果我禁用写入会话对象的行并使会话的读取保持不变,则错误消失:

        # self.session[cnt_key] = str(cnt)

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

get_session的第一个参数是名称,如果您想更改默认值。您正在传递响应对象,这是错误的。

@webapp2.cached_property
def session(self):
    return self.session_store.get_session(backend='datastore')