Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for a cookie with Python Flask

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?

like image 599
Jimmy Avatar asked Nov 23 '12 14:11

Jimmy


People also ask

How do I check my cookies in Flask?

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.

How does Flask help with cookies?

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.

How do I clear my Flask cookies?

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.

Does Flask session use cookies?

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.


2 Answers

request.cookies is a dict, so:

from flask import request  if 'country' in request.cookies:     # do something else:     # do something else 
like image 120
Jon Clements Avatar answered Oct 04 '22 13:10

Jon Clements


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

like image 37
Peter Graham Avatar answered Oct 04 '22 13:10

Peter Graham