Web development with python #4 : Store cookie and Get cookie in template

in #utopian-io5 years ago (edited)

Repository

https://github.com/python

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

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 this resp.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 and request.form['email'] is the value.

  • And I will return return resp, for more details we can see examples like the picture below:

ezgif.com-video-to-gif (3).gif

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 on request.cookies and we can use get() 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:

Screenshot_5.png

  • 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:

ezgif.com-video-to-gif (4).gif

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

Proof of work done

https://github.com/milleaduski/python-web-app

Sort:  

Coin Marketplace

STEEM 0.39
TRX 0.12
JST 0.040
BTC 70463.21
ETH 3549.83
USDT 1.00
SBD 4.87