Check for a cookie with Python Flask

Question:

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?

Asked By: Jimmy

||

Answers:

request.cookies is a dict, so:

from flask import request

if 'country' in request.cookies:
    # do something
else:
    # do something else
Answered By: 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

Answered By: Peter Graham
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.