From the webapp2 documentation
I've gotten the following code (not sure it is correct):
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()
class Login(BaseHandler):
def get(self):
self.session['foo'] = 'bar'
foo = self.session.get('foo')
I'm just trying to create a basic login session once a User logs in. But I've been researching this for quite a while with no luck.
What I think is going on:
self.session_store = sessions.get_store(request=self.request)
Getting a session store where I will store the required data of the user
try:
webapp2.RequestHandler.dispatch(self)
finally:
self.session_store.save_sessions(self.response)
Updating the session store? Not entirely sure here.
@webapp2.cached_property
def session(self):
return self.session_store.get_session()
Returning the session so the data inside can be used
What I don't know:
request=self.request
in the get_store()
function? Can't the store be a general store in the servers database which stores sessions?try,finally:
bit for. Very confused there.I apologies if there are a lot of questions, but I'm very new and lost. I watched some PHP sessions tutorials but haven't made much headway.
Thanks for any answers in advance.
That just passes the current value of self.request
as the "request" keyword argument for get_store. I don't know what the second part of that question means.
This just ensures that even if an exception happens within the try block (ie inside your handler code) the finally block will always be executed, so the session store will always be saved.
You should have nothing whatsoever to do with session IDs; they are completely opaque. They just relate to an ID the user stores in their cookie. But the relationship to Users is the other way round; as I said on your last question, you would store the db ID of the User record in the session when they log in.
Both questions 1 and 2 are really just standard Python; you might benefit from going through a language tutorial.