Web development with python #4 : Store cookie and Get cookie in template
Repository
What Will I Learn?
- Store cookie in Flask
- Get a cookie and render in the template
Requirements
- Basic Python
- Install Python 3
- Install Flask
Resources
- Python - https://www.python.org/
- Flask - http://flask.pocoo.org/
- Jinja2 -http://jinja.pocoo.org/docs/2.10/
Difficulty
Basic
Tutorial Content
This tutorial is a continuation of the tutorial series on building web applications with python. so for those of you who don't have basic about python, I suggest you follow the previous tutorial in the curriculum below. In the previous tutorial, we have learned the get method and about url_for. In this tutorial, we will learn cookies on the flask and we will also make a login with the flask using the session.
Cookie in Flask
On a website a cookie is often used to store data on a client computer. cookies are often used to store web data into our client's computer, so that when we visit the web for the first time and so on the web is still in the same state. in this section we will learn how to use cookies on the web application that we make with flasks, In the previous tutorial we created a routing /login
that have the get and post method:
@app.route('/login', methods=["GET", "POST"])
def login():
if request.method == "POST":
return "Your email is "+ request.form['email']
return render_template('login.html')
- Use the
make_response
library
To make a Cookie on the flask we need help from themake_response
library. When installing flask we have also installed make_response automatically. but we need to import it as follows:
app.py
from flask import Flask, render_template, request, make_response
@app.route('/login', methods=["GET", "POST"])
def login():
if request.method == "POST":
return "Your email is "+ request.form['email']
return render_template('login.html')
import library make_response
to use cookies on the flask we need tools from the make_response
library. This library is automatically installed when we install the flask. All we need to do is import it. to import it we can do it like the following:
app.py
from flask import Flask, render_template, request, make_response
After we import it we can use the library to make cookies as follows:
@app.route('/login', methods=["GET", "POST"])
def login():
if request.method == "POST":
resp = make_response("Your email is "+ request.form['email'])
resp.set_cookie('email_user', request.form['email'])
return resp
return render_template('login.html')
After we have imported the make_response library now we can use it like this
make_response ()
. This function is used to make a response based on the parameters that we passed to this function. In this tutorial, we will respond to'email_user', request.form ['email']
. We will give a response from the email we have 'POST' by input, you can see the explanation in this tutorial.After we made a response, now we can make a cookie from the response from the
make_response()
function. We can set cookies like thisresp.set_cookie('email_user', request.form['email'])
. to set cookies we need to make a combination of keys and values,'email_user'
is the key andrequest.form['email']
is the value.And I will return
return resp
, for more details we can see examples like the picture below:
We can see in the picture above, cookies have been stored in our browser. Cookies are not always saved, because cookies have an expiration period.
- get cookie
We have succeeded to save the cookies, of course, we don't just want to save the cookie, we also want to use it and get the value. in this section, we will do it. we will switch to route '/welcome'
, so we can see the used cookie on different pages.
app.py
@app.route('/welcome')
def homeFunction():
email = request.cookies.get('email_user')
return render_template('index.html', email = email)
We can use the request method to retrieve all
request
data. Because we want to get a cookie, we can use its function onrequest.cookies
and we can useget()
to get the cookie with the key of the cookie.to get the cookie value we can use the function
request.cookies.get()
, to get the value we can pass the key of the cookie we want to get. 'email_user' is the key of the cookie, You can see the picture below:
- We will try to show the value of the user's email cookie to another page, we will pass the value on page index.html
return render_template('index.html', email = email)
. We pass the data with variable email. the following is the contents of index.html:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Template Jinja2</title>
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles.css')}}">
</head>
<body>
<a href="{{ url_for('homeFunction')}}">Home</a>
<a href="{{ url_for('profFunc')}}">Profile</a>
<a href="{{ url_for('login')}}">Login</a>
<h1 class="title">Welcome to my profile {{email}}</h1>
</body>
</html>
We can print out the data like this {{email}}
and we can see the example as shown below:
We can see in the picture above we has been successful in retrieving the value of cookies stored in our browser, cookies are used to store data that is not sensitive or dangerous. We have learned how to use cookies on flasks based on python, Next tutorial I will discuss about the login system on the flask. I hope this tutorial can help you, see you in the next tutorial. thank you
Curriculum
Web developement with python #1 : Flask initialization and Routing system
Web development with python #2 : Templating jinja2 and Method POST on routing system
Web development with python #3 : Get method, Query parameter and Navigate Routing
I thank you for your contribution. Here are my thoughts. Note that, my thoughts are my personal ideas on your post and they are not directly related to the review and scoring unlike the answers I gave in the questionnaire;
Structure
Language
Some of your sentences are artificial. This makes them hard to read and understand. To overcome that, I advise you to check the structure of your sentences. For example, using "we" for each sentence in the post makes it boring to read.
There are some sentences which are hard to understand because of the vocabulary and grammar. I advise you to proofread your posts before posting. It can increase the efficiency of your post.
Content
Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.
To view those questions and the relevant answers related to your post, click here.
Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]
Thank you for your review, @yokunjon! Keep up the good work!
Hey, @duski.harahap!
Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!
Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).
Want to chat? Join us on Discord https://discord.gg/h52nFrV.
Vote for Utopian Witness!