Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask: How to remove cookies?

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?

like image 691
Oliver Avatar asked Jan 17 '13 19:01

Oliver


People also ask

What are cookies in Flask?

Flask – Cookies A cookie is stored on a client's computer in the form of a text file. Its purpose is to remember and track data pertaining to a client's usage for better visitor experience and site statistics. A Request object contains a cookie's attribute.

How do I unset a session cookie?

If you want to unset all of the values, you can just run a session_destroy() . It will unset all the values and destroy the session. But the $_SESSION array will still work in the same page after session_destroy() . Then you can simply run $_SESSION = array() to reset it's contents.

How do you delete cookies in Python?

def delete_cookie(cookie_name): """Pass the name of the cookie you want deleted and this function will delete it."""

Are Flask cookies secure?

The browser will never send secure cookies with requests that are not encrypted. With Flask, you can control the secure flag on the session cookie with the SESSION_COOKIE_SECURE configuration setting. By default, it is set to False , which makes the session cookie available to both HTTP and HTTPS connections.


2 Answers

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.

like image 124
Eevee Avatar answered Oct 02 '22 08:10

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

like image 27
Reck Avatar answered Oct 02 '22 06:10

Reck