Saving Webapp2 Sessions on GAE

I am having problems storing session variables in the webapp2 session store when working in GAE. I created a super simple application to reproduce the problem:

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) 

The premise is that the get request sets the session variable, and post just records the response object.

I understand that after the get request is complete, the session is saved myvalue . After that, if I execute the post request, then the get request again, myvalue should still be there, although I did not set it again in the post handler. Alas, this is not so:

 >>> 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! 
+2
source share
1 answer

Since I'm pretty new to web technologies and standards, I seem to be missing something:

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

This is an implementation of SecureCookie . Since the cookie is not saved in the response, if it is not changed, I assume that in the standard / protocol the backend is not responsible for sending the cookie again, since it should already be on the client. It would be great to find a link to this.


This proves this (switching to 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 >>> 
+3
source

All Articles