Search code examples
pythongoogle-app-enginewebapp2

remember me option in GAE python


I am working on a project in which i am working on a signup/login module. I have implemented the sessions in webapp2 python successfully. Now i want to implement the remember me feature on login. I am unable to find anything which can help me. I do know that i have to set the age of session. But i do not know how. Here is my session code.

def dispatch(self):

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

    try:
        # Dispatch the request.
        webapp2.RequestHandler.dispatch(self)
    finally:
        # Save all sessions.
        self.session_store.save_sessions(self.response)

@webapp2.cached_property
def session(self):
    # Returns a session using the default cookie key.
    return self.session_store.get_session()

Config:

config = {}
config['webapp2_extras.sessions'] = {
    'secret_key': 'my-super-secret-key',
}

Kindly help me.


Solution

  • First in case you don't know the difference between sessions and cookies

    What is a Cookie? A cookie is a small piece of text stored on a user's computer by their browser. Common uses for cookies are authentication, storing of site preferences, shopping cart items, and server session identification.

    Each time the users' web browser interacts with a web server it will pass the cookie information to the web server. Only the cookies stored by the browser that relate to the domain in the requested URL will be sent to the server. This means that cookies that relate to www.example.com will not be sent to www.exampledomain.com.

    In essence, a cookie is a great way of linking one page to the next for a user's interaction with a web site or web application.

    .

    What is a Session? A session can be defined as a server-side storage of information that is desired to persist throughout the user's interaction with the web site or web application.

    Instead of storing large and constantly changing information via cookies in the user's browser, only a unique identifier is stored on the client side (called a "session id"). This session id is passed to the web server every time the browser makes an HTTP request (ie a page link or AJAX request). The web application pairs this session id with it's internal database and retrieves the stored variables for use by the requested page.

    If you want to implement something like "remember me" you should use cookies because data stored in session isn't persistent.

    For setting and getting cookies in webapp2:

    response.headers.add_header('Set-Cookie', 'remember_me=%s' % some_hash)
    
    request.cookies.get('remember_me', '')
    

    I strongly recommend you to read this article that has explained this stuff thoroughly.