在GAE上坚持Webapp2会话

时间:2014-08-10 05:56:40

标签: python google-app-engine session webapp2

在GAE上运行时,我无法在webapp2会话存储中保存会话变量。我创建了一个超级简单的应用程序来重现这个问题:

class MainHandler(webapp2.RequestHandler):

    def post(self):

        session = self.session_store.get_session()

        previous_value = session.get("myvalue")
        self.response.write(previous_value)

    def get(self):

        session = self.session_store.get_session()

        previous_value = session.get("myvalue")
        self.response.write(previous_value)

        session["myvalue"] = "Hi! " + (previous_value if previous_value else "")

    # this is needed for webapp2 sessions to work
    def dispatch(self):

        # Get a session store for this request.
        self.session_store = sessions.get_store(request=self.request)

        try:
            super(MainHandler, self).dispatch()

        finally:
            # Save all sessions.
            self.session_store.save_sessions(self.response)

这里的前提是get请求设置会话变量,而post只是写入响应对象。

我的理解是,在执行get请求后,会话仍然存在myvalue。之后,如果我执行post请求,然后再次get请求,myvalue仍然应该在那里,即使我没有在post中再次设置它处理程序。唉,事实并非如此:

>>> cookies = None
>>> for i in range(10):
...     r = requests.get("http://localhost:11282/", cookies=cookies)
...     cookies = r.cookies
...     print r.text
... 
None
Hi! 
Hi! Hi! 
Hi! Hi! Hi! 
Hi! Hi! Hi! Hi! 
Hi! Hi! Hi! Hi! Hi! 
Hi! Hi! Hi! Hi! Hi! Hi! 
Hi! Hi! Hi! Hi! Hi! Hi! Hi! 
Hi! Hi! Hi! Hi! Hi! Hi! Hi! Hi! 
Hi! Hi! Hi! Hi! Hi! Hi! Hi! Hi! Hi! 
>>> 
>>> cookies = None
>>> for i in range(10):
...     r = requests.get("http://localhost:11282/", cookies=cookies)
...     cookies = r.cookies
...     print r.text
...     r = requests.post("http://localhost:11282/", cookies=cookies)
...     cookies = r.cookies
...     print r.text
... 
None
Hi! 
None
Hi! 
None
Hi! 
None
Hi! 
None
Hi! 
None
Hi! 
None
Hi! 
None
Hi! 
None
Hi! 
None
Hi!

1 个答案:

答案 0 :(得分:3)

由于我对网络技术和标准还不熟悉,我似乎错过了一些东西:

def save_session(self, response):
    if self.session is None or not self.session.modified:
        return

这是SecureCookie的实施。由于如果未修改cookie,cookie不会保存到响应中,我猜测每个标准/协议,后端不负责再次发送cookie,因为它应该已经在客户端上。找到对此的参考将是很好的。


这证明了它(切换到requests.Session()):

>>> s = requests.Session()
>>> for i in range(5):
...     r = s.get("http://localhost:11282/")
...     print r.text
...     r = s.post("http://localhost:11282/")
...     print r.text
... 
None
POST
Hi! 
POST
Hi! Hi! 
POST
Hi! Hi! Hi! 
POST
Hi! Hi! Hi! Hi! 
POST
>>>