Part 6 - πŸͺ Cookies in Flask

October 13th, 2020 3 min read

What are cookies ?

Cookies are a kind of storage, but a very small storage. It is mainly used to store small information such as csrf_token, preferences, site statics and/or user activities. By using cookies one can provide an immersive experice to the users of the websites by making the website more personalized for them.

How to use β€œCookies” in Flask ?

In flask using cookies is super simple. In flask cookies are Immutable Dictionary, we can also call as a dictionary. To view the value of the request.cookies attribute it will return an dictionary object. Let’s see an understand it with an example,

app.py

from flask import Flask, request, make_response, redirect, url_for, render_template

app = Flask(__name__)

@app.route("/")
def home():
	userName = request.cookies.get("name")
	if userName:
		return f"Hello {userName}."
	else:
		return redirect(url_for("setName"))


@app.route("/set-name", methods = ['GET', 'POST'])
def setName():
	if request.method == "POST":
		name = request.form.get("name")
		resp = make_response(redirect(url_for("home")))

		# Now Let's Add A Cookie
		resp.set_cookie("name", name)

		return resp
	return render_template("setName.html")

if __name__ == '__main__':
	app.run(debug=True)

setName.html

<form action="/set-name" method="POST">
	<input type="text" name="name">
	<button type="submit"> Add Name </button>
</form>

This is a pretty simple application what it does is it when you visit it ( on homepage ), it checks whether the cookie has the value for name , you may notice that we have used request.cookies.get("name") format instead of request.cookies["name"] and it has a reason and that reason is if we would have second method it would have given us error and our view would return error, but as we used the first method intead it returned '' i.e. a blank string.

Till this point you may be damn clear to that to view cookie value we the following syntrax request.cookies.get("name").

Now let’s see how to write the data to a cookie, as you may have seen in the home route that if name was not found we redirect users to setName route. Here if request.method is GET we return setName.html and if the method is POST we get value of name from the form and if name exists we set value of cookie for name attribute to value of name.

To set the value of cookie do the following steps:

  1. Create a response object.

To create a respose object just use make_response from flask to set response and set any kind of response which may include render_template, redirect or whichever you want just make sute it is valid and store it in a varible.

  1. Set the Value.

Use set_cookie method on that varible and use the following syntrax to the cookie resp.set_cookie("name", value) where "name" is name of your attribute and value is its value.

  1. Return the response.

Return that varible as a reponse.

If you are wondering how to use forms in flask the check out πŸ†• Get and Post requests in Flask 🍾.

Hope you like it 😍. Thank You 😊.


You may also like: