Menu Close

Flask Cookies Tutorial

Flask Cookies

In this article, you will learn all about flask cookies with the help of examples so that you don’t have any confusion regarding flask cookies.
In the previous flask tutorial, we have covered all about flask request objects with the help of examples.

Note:- To understand flask coding, you should have basic knowledge of Python programming.

Flask Cookies

An HTTP cookie ( also called web cookie, Internet cookie, browser cookie, or simply cookie ) is a piece of data stored on the user’s computer by the web browser while visiting the website.

Cookies were designed for websites to store or remember some useful information of the user or to store the user browsing activity. They can also be capable of storing previously entered user information in the form fields such as name, address, password and payment details, etc.

Cookies are always generated by the server on the user computer to store the user information for a better user experience when the user returns again. Cookies are only stores on the client machine, not the server. cookies are live until expiry.

In Flask, cookies are associate with the flask request object as the dictionary object. A Python dictionary object contains cookie information in the form of the key and value.

Syntax

Response.set_cookies(key, value, max_age, expires, path, domain, secure, httponly, sametime)

Parameters

Flask also provides a facility to set the expiry time of the cookies.

  • key:- The name ( key ) of the cookie to be set.
  • value:- The value of the cookie or name or key.
  • max:- This represents the age of the cookie. It should be a number of seconds.
  • expires:- Expiry time of the cookie. it should be a DateTime object or UNIX timestamp.
  • path:- Limit the cookie to be given path.
  • domain:- This is for setting the cross-domain cookie.
  • secure:- If True, the cookie will only available for HTTPS. Default is False.
  • httponly:- Disallow JavaScript access to the cookie.
  • sametime:- It defines the limit of the scope of the cookie to be only attached to requests that are on the same site.

Set Flask Cookies

In Flask, Cookies are set by using the response object method that is set_cookie(). Let’s see the complete process of creating cookies in the flask.

main.py


from flask import Flask, make_response

#Create the object of the Flask class.
app= Flask(__name__)

@app.route("/home")
def Home():
    res = make_response("<h1> Cookie is set successfully....</h1>")
    res.set_cookie('name', 'ProgrammingFunda', )
    return res

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

When you will execute the above flask script and navigate http://127.0.0.1:5000/home address, Then the cookie will be set with key ‘name‘ and value ‘ProgrammingFunda‘.

Access Flask Cookie

To access the flask cookies, the flask provides a cookies parameter that returns the dictionary contains all the cookies transmitted with the request.


@app.route("/get_cookie")
def get_cookie():
    cookie_data = request.cookies
    return cookie_data

The above example will return a dictionary with all the cookies, like below.

{
  "csrftoken": "VNlg8OJAGiehGXZts5WNxLkYmKJYrgdxBMg3RVc6ztWrPK6JW6YMjmd5QxoBlUPm", 
  "name": "ProgrammingFunda"
}

To access any particular cookie, consider the below example.


@app.route("/get_cookie")
def get_cookie():
    cookie_data = request.cookies.get('name')
    return 'Cookie is ' + cookie_data

Flask Login application

Here we will create a simple login flask application where user can enter their username, email, and password and login, after login users can see their profile.

In this flask application, we will use the concept of cookies to set and get the cookies.

login.py


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

#Create the object of the Flask class.
app= Flask(__name__)
  
       
@app.route("/error")   
def error():
    return "Something went wrong, please try again.."
    
@app.route("/success", methods=['POST'])    
def success():
    if request.method == 'POST':
        username = request.form['username']
        email = request.form['email']
        password = request.form['password']        
        if email != '' and password != '':
            res = make_response(render_template("done.html"))
            res.set_cookie("email", email)
            res.set_cookie("username", username)
            return res
            
        else:
            return redirect(url_for('error'))
             
@app.route("/login", methods=['GET'])
def login():
    return render_template("login.html")
    
@app.route('/user_profile')
def user_profile():
    data = request.cookies
    return f"Your username and email are:- {data.get('username')} and {data.get('email')}"

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

login.html

<html>
<head>
<title>
Flask login application
</title>
</head>
<body>

<h1>User Login Form</h1>

<form method="POST" action="/success">
<label>User name:- </label>
<input type="text" name="username" placeholder="Enter your email"><br><br>
<label>Email:- </label>
<input type="email" name="email" placeholder="Enter your email"><br><br>
<label>Password:- </label>
<input type="password" name="password" placeholder="Enter your password">
<br><br>
<button type="submit">Login</button>
</form>
</body>
</html>

done.html

<html>
<head>
<title>
Flask login application
</title>
</head>
<body>
<h1>Login successfully...</h1>
<p><a href="/user_profile">Click Here</a> to see profile</p>
</form>
</body>
</html>

Conclusion

In this flask cookies tutorial, you have learned all about what is flask cookies and also you have learned how to set and get cookies. Basically, a cookie is a piece of data store on the visitor’s computer while the user visiting a website.

If you like this flask cookies tutorial, please share and keep visiting for further flask tutorials.

Reference:- Click Here

Flask Request Object
Python Flask Tutorial for Beginners 2024

Related Posts