Python Web development tutorial using Flask – session & cookies

pyhon-for-web-development-tutorial

In this tutorial, you are going to learn session and cookies in flask for web development, Cookies and session play a important role in Web development, cookies is use to store data in client side on browser in a simple text files. Cookies are used for user experience, track data activities for some suggestions.

In flask, cookies are set by using the set_cookie() method on the response object. The response object can be formed by using make_response() method.

The session is the same as cookies, In session, data is stored on the server cryptographically by setting the session variable session['email'] = "[email protected]"

Here is the example of account login with cookies and sessions:-

In below example we first start with session secret_key which is set by app.secret_key = "abhi" then in route ‘/’ login.html form file render, when the form is submitted the submit method make response success and set the cookie, here session is set in the next line.

from flask import Flask, render_template, request, make_response, session

app = Flask(__name__)
app.secret_key = "abhi"

@app.route('/')
def home():
    return render_template("login.html")

@app.route('/submit', methods = ['POST'])
def submit():
    input = request.form
    res = make_response("Login Successfully!<br/><a href='/view'>View</a>")
    res.set_cookie('email', input['email'])
    session['email'] = input['email']
    return res
  
@app.route('/view')
def view():
    email = request.cookies.get('email')
    if 'email' in session:
        e = session['email']
    resp = make_response(render_template('view.html',email = email, e = e))
    return resp

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

Form login.html:-

<html>
    <head>
        <title>Login Form</title>
        <style>
            body{
                background: #ddd;
            }
            h1{
                color: blueviolet;
            }
        </style>
    </head>
    
    <body>
        <center>
            <h1>Login Form</h1>
            <form action="/submit" method="post">
                <p>Email : <input type="text" value="" name="email" required/></p>
                <p>Password : <input type="password" name="password"/></p>
                <p><input type="submit" value="Submit"/></p>
            </form>
        </center>
    </body>
</html>

View.html(this will show the session and cookies data)

<html>
<title>View Session Cookie</title>
Cookies save email = {{email}}<br/>
Session save email = {{e}}
</html>
Cookies and session set, Login success!

The view method use request.cookies.get('email') to store the value in email, check the value email is found in session or not the store in “e”, then render the data in view.html by using method make_response(render_template('view.html',email = email, e = e))

fetch Cookies and session data

We learn in this tutorial how to use session and cookies in flask (web development for python) by using a example of creating a login form and storing the cookie and session value.

And also learned how to show/fetch cookie and session data which is displayed on view.html file.

Happy Pythoning! 👍❤

Python for Web Development file uploading save in MySQL Flask
Python Web development tutorial using Flask

Leave a Reply

Your email address will not be published. Required fields are marked *