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?
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.
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.
def delete_cookie(cookie_name): """Pass the name of the cookie you want deleted and this function will delete it."""
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With