I would like to get a cookie (e.g. country
) with this Flask call.
data = request.cookies.get("country")
How can I tell if the cookie exists?
In Flask, cookies are set on response object. Use make_response() function to get response object from return value of a view function. After that, use the set_cookie() function of response object to store a cookie. Reading back a cookie is easy.
Flask facilitates us to specify the expiry time, path, and the domain name of the website. In Flask, the cookies are set on the response object by using the set_cookie() method on the response object. The response object can be formed by using the make_response() method in the view function.
Python Flask- Delete Cookies To delete a cookie call set_cookie() method with the name of the cookie and any value and set the max_age argument to 0.
In order to store data across multiple requests, Flask utilizes cryptographically-signed cookies (stored on the web browser) to store the data for a session. This cookie is sent with each request to the Flask app on the server-side where it's decoded.
request.cookies
is a dict
, so:
from flask import request if 'country' in request.cookies: # do something else: # do something else
request.cookies.get('my_cookie')
should have worked. If it didn't work, you may not have access to the request object when you call this line.
Try importing flask at the top
import flask
then call
cookie = flask.request.cookies.get('my_cookie')
If the cookies exists, it will get assigned to cookie
and if not then cookie
will equal None
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