How do I store cookies with Flask?

Question:
How do I store and access cookies with Flask?

1 Like

Hi @RedCoder ! The answer to your question is from the Flask documentation.

Reading cookies:

from flask import request

@app.route('/')
def index():
    username = request.cookies.get('username')
    # use cookies.get(key) instead of cookies[key] to not get a
    # KeyError if the cookie is missing.

Storing cookies:

from flask import make_response

@app.route('/')
def index():
    resp = make_response(render_template(...))
    resp.set_cookie('username', 'the username')
    return resp

Note that cookies are set on response objects. Since you normally just return strings from the view functions Flask will convert them into response objects for you. If you explicitly want to do that you can use the make_response() function and then modify it.

A source: Quickstart — Flask Documentation (3.0.x)

3 Likes

Greetings, @RedCoder. Are you inquiring about the process of creating and assigning values to cookies in a Python Flask application? Alternatively, is your question centered around retrieving cookies using Flask and securely storing them in a designated location?