How to set cookie in Python Flask?

Question:

In this way, I want to set my cookie. But it fails to set.

@app.route('/')
def index():
    res = flask.make_response()
    res.set_cookie("name", value="I am cookie")

When I print res it shows <Response 0 bytes [200 OK] But not set cookie

Asked By: Shaon shaonty

||

Answers:

You have to return the response after setting the cookie.

@app.route('/')
def index():
    resp = make_response(render_template(...))
    resp.set_cookie('somecookiename', 'I am cookie')
    return resp 

This way a cookie will be generated in your browser, but you can get this cookie in the next request.

@app.route('/get-cookie/')
def get_cookie():
    username = request.cookies.get('somecookiename')
Answered By: Sahid Hossen

The cookie you set will be visible if you either use other tools to see it (ex: Press F12 for Developer Tools in Firefox or Chrome) or use a piece of code of JavaScript inside the rendered response.

The cookies are set on the browser by either browser itself (JavaScript) or as a response from a server.

The difference is of great importance as even if the cookie is set by the server the cookie might not be set on the browser (ex: cases where cookie are completely disabled or discarded).

So even if the server might tell "I set up the cookie" – the cookie might not be present on the browser.

For the server to be sure that the cookie was set a subsequent request from the browser is needed (with the cookie present in the request’s headers).

So even if the Flask’s response (res variable) will mention that the cookie is set we can only be sure that it was set by the server but it will have no confirmation about it from the browser.

Advanced
Another aspect is about how Flask or any other API is creating the responses. As the payload (html/template code) and headers (cookie) are set at same time – the "code" inside the payload (html/template code) might not have access to the cookie.
So you might not be able to set a cookie and display it in the response.

An idea might be to (be able to) first set the cookies and THEN to render the context and the order of setup to be important – so that the html/template to be aware of already setup values. But even in this case is only the server’s confirmation that it set up the cookie.

A solution

@app.route('/')
def index():
    res = flask.make_response()
    res.set_cookie("name", value="I am cookie")

    # redirect to a page that display the cookie
    resp.headers['location'] = url_for('showcookies') 

    return resp, 302
Answered By: Alex

This response will set cookie in you browser

def func():
    response = make_response( render_template() )
    response.set_cookie( "name", "value" )
    return response
Answered By: Tanmay Rauth
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.