Flask: How to remove cookies?

Question:

I set cookies with the code suggested in the docs:

from flask import make_response

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

But how do I remove them? There is no remove_cookie method. I tried:

if request.cookies.get('sessionID');
    request.cookies.pop('sessionID', None)

but it turns out that the request.cookies object is immutable. What do I do?

Asked By: Oliver

||

Answers:

You need to set the cookie with an expiry that’s in the past.

resp = make_response(render_template(...))
resp.set_cookie('username', expires=0)
return resp

By the way, I hope you don’t actually expect that username cookie to be safe. Because it’s not. The user can put anything he wants in there. The solution is usually to use the Flask session which uses a signed cookie that cannot be modified by the user.

Answered By: ThiefMaster

There’s no HTTP header for deleting a cookie. Traditionally you just set the cookie to a dummy value with an expiration date in the past, so it immediately expires.

resp.set_cookie('sessionID', '', expires=0)

This will set the session id cookie to an empty string that expires at unixtime 0, which is almost certainly in the past.

Answered By: Eevee

We can make us of delete_cookie() available from flask.Response.

resp.delete_cookie('username')

This will delete the cookie on response.
Here is delete_cookie documentation.

Also you may want to have add path (default set to ‘/’) and domain (default set to None).

resp.delete_cookie('username', path='/', domain='yourdomain.com')

Here is the interpreter screenshot which shows delete_cookie object in flask.Response.

Python Interpreter Screenshot

Answered By: Reck
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.