Search code examples
pythoncookiesflask

How to set cookie in Python Flask?


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


Solution

  • 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')