Search code examples
pythonapacheflasksession

How to specify where flask should store cookies (flask Session)


I use Flask to host my python-based web application, through Apache2 on a linux server. By default, flask session stores its cookies on the root directory under /flask_session/.

I want to instead store the cookies within the application folder, i.e. /var/www/webApp/webApp/cookies/ .

After reading the flask documentation , I thought that doing

app.config["SESSION_COOKIE_PATH"] = "/var/www/webApp/webApp/cookies/"

should achieve this, but it does not work, and

app.config["APPLICATION_ROOT"] = "/var/www/webApp/webApp/"

does not affect anything either: the cookies are still put in /flask_session/

In both cases I pass Session the app only after the config:

Session(app)

Solution

  • Firstly, we should clarify that flask does not store 'cookies' locally. Cookies are a client-side mechanism (typically a browser), and all storage is expected to happen on the client side - not in flask.

    Another point: by default, flask will store all session data within the cookie. Which means that session data will also be stored by the client. There are plugins available to change this behavior and have the session data stored on the server - and not in the cookie. Flask-Session is one such library, and it appears that is what you are using (please correct me if that isn't the case).

    With that out the way, we can get to your actual question which is: "How can we get Flask to store the session data in a custom directory instead of the default (/flask_session/)?"

    Per the documentation, the SESSION_FILE_DIR config is where this would be set:

    SESSION_FILE_DIR | The directory where session files are stored. Default to use flask_session directory under current working directory.

    So this code should do what you are looking for:

    app.config["SESSION_FILE_DIR"] = "/var/www/webApp/webApp/"