Flask: How to remove cookies?


I set cookies with the code suggested in the docs:

from flask import make_response

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?

1/17/2013 7:08:21 PM

Accepted Answer

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.

1/17/2013 7:15:09 PM

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow