Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Some questions about Flask sessions

Consider the following simple flask app:

from flask import Flask, request, session

application = Flask(__name__)
application.secret_key = "some_random_string"

@application.route("/enter_string")
def start_session():
    session["string"] = request.args["string"]

@application.route("/get_string")
def continue_session():
    if "string" not in session:
        return "Give me a string first!"

    return "You entered " + session["string"]

if __name__ == "__main__":
    application.debug = True
    application.run()

Here are my questions:

  1. Once the "enter_string" endpoint has been visited and the user has assigned a string to session["string"], where is the string stored? Is it in the server's memory or the user's?
  2. By default, the session expires when the browser exits. Is there a simple way to have some other event trigger the expiration of the session, such as closing the window but not necessarily the browser?
  3. By default, will the session ever time out or is it kept until the browser exits no matter how long that takes?
like image 243
Paul Siegel Avatar asked Oct 13 '15 21:10

Paul Siegel


1 Answers

Sessions in Flask can be implemented in different ways. The default implementation is based on secure cookies (cookies that have a cryptographic signature that prevents tampering). Here are the answers to your questions for this implementation:

  1. The string will be stored in a client-side cookie. Each time the browser sends a request to the server, the cookie will be sent along with it.

  2. The client can destroy the session by deleting the cookie using Javascript. (The default name for the session cookie is session). The server can delete the session by removing all the items from it.

  3. In the default implementation the cookie has an expiration date set 31 days in the future. This can be changed with the PERMANENT_SESSION_LIFETIME configuration setting.

As I mentioned above, Flask supports third party session handlers, so the above answer may not apply to other implementations. In particular, there are handlers that implement server-side sessions (such as Flask-Session or Flask-KVSession) that store the session data in the server instead of the client.

like image 140
Miguel Avatar answered Oct 17 '22 20:10

Miguel