Expert-led Online Courses: Elevate Your Skills, Get ready for Future - Enroll Now!
In this article, we will learn about cookies in flask, how to set, get and remove cookies and much more. Let’s start!!!
Flask Cookies
Python was used to create the lightweight Flask web development framework. Normally, we use HTML, CSS, and JavaScript to create websites, but flask uses the Python programming tool to develop web apps.
When you visit a website, cookies are small text files that the website saves to your mobile device or computer. To make it run better and offer services catered to our interests, the cookie stores data about our visit. Additionally, cookies can be used to save user settings like translation or regional preferences. Cookies benefit users by improving their experience, increasing website efficiency, and identifying returning users.
On the client’s computer, the cookies are kept as text files. Cookie is implemented to track a user’s online activity and display suggestions based on the user’s preferences to improve the user experience.
Cookies are placed on the client’s computer by the server and linked to their requests to that host in subsequent transactions until the cookie expires or is deleted.
In Flask, the dictionaries collection of all cookie parameters and associated values sent by the client is connected to the Requests object as the cookie object. We may provide the website’s domain name, path, and expiration time with the help of Flask.
A text file in the format of a cookie is kept on a client’s computer. To improve user satisfaction and site statistics, it is designed to store and track information about a client’s usage.
An attribute of a cookie can be found in a Request object. A user has sent a dictionary object that contains all of the cookies variables and their respective values. A cookie also keeps track of the site’s domain name, path, and expiration time.
Cookie is set on the response object in Flask. To obtain a response object from a view function’s return value, use the make response() function. After that, you can store a cookie using the response object’s set cookie() function.
It’s simple to read a cookie back. the request method get(). To read a cookie, use the cookies attribute.
Setting Cookies in Flask
The set cookie() function on the return object in Flask is used to set cookies on the object. The make response() function in the view procedure can be used to create the response object.
from flask import *
app = Flask(__name__)
@app.route('/method')
def method():
res = make_response("<h1>Setting Cookies</h1>")
res.set_cookie('foo','bar')
return res
if __name__ == '__main__':
app.run(debug = True)
The python script mentioned above can be used to create a cookie on the computer for the localhost:5000 website with the name “foo” and the content “bar.” Execute this Python code by typing python script.py, then check the browser for the outcome.
Removal of cookies from the flask
Cookies may also be deleted. To delete a cookie, use set cookie() with any value and the max age argument set to 0. Just after cookie() view function in the server.py file, add the following code.
@app.route('/delete-cookie/')
def remove():
res = make_response("Successfully Removed Cookie.")
res.set_cookie('foo', 'bar', max_age=0)
return res
How to get cookies in flask
This get() method uses the request object to acquire the cookie value from the user’s web browser.
from flask import Flask, request, make_response
app = Flask(__name__)
# getting cookie from the previous set_cookie code
@app.route('/get')
def get():
Data = request.cookies.get('Data')
return 'You have some access to '+ Data
app.run()
Application for Flask Login
Here, we’ll build a login application using Flask, where the user is presented with a login screen (login_page.html) that asks them to input their email and password. The application will send the client to the victory page (success.html), in which the greeting and a hyperlink to the account (account.html) are provided, if indeed the password is “jtp,” else it will send them to the error page.
login_page.py
from flask import *
app = Flask(__name__)
@app.route('/error')
def error():
return "<p><strong>Enter your password</strong></p>"
@app.route('/')
def login_fun():
return render_template("login_page.html")
@app.route('/success',methods = ['POST'])
def success():
if request.method == "POST":
email = request.form['email']
password = request.form['pass']
if password=="jtp":
resp = make_response(render_template('successful.html'))
resp.set_cookie('email',email)
return resp
else:
return redirect(url_for('error'))
@app.route('/profile_view')
def account():
email = request.cookies.get('email')
resp = make_response(render_template('account.html',name = email))
return resp
if __name__ == "__main__":
app.run(debug = True)
login_page.html
<html>
<head>
<title>Login page</title>
</head>
<body>
<form method = "post" action = "http://localhost:5000/success">
<table>
<tr><td>Email Id</td><td><input type = 'email' name = 'email'></td></tr>
<tr><td>enter Password</td><td><input type = 'password' name = 'pass'></td></tr>
<tr><td><input type = "submit" value = "Submit"></td></tr>
</table>
</form>
</body>
</html>
success.html
<html>
<head>
<title>Successful</title>
</head>
<body>
<h2>Successfully Logged In.</h2>
<a href="/viewprofile">View Profile</a>
</body>
</html>
account.html
<html>
<head>
<title>Account</title>
</head>
<body>
<h3>Hello, {{name}}</h3>
</body>
</html>
Counting website visitors with cookies
The code below asks for the quantity of people who have visited our website. By using cookies, we first retrieve the number of visitors. However, the visitor count variable we previously made does not exist. According to the database collection in Python, this key (visitors count) would take the value of zero since it is not existent in the dictionary. As a result, the count is increased when a user visits the page, starting at 0 for first-time users. The response object is obtained by using make response(), which is also where the cookie is set.
from flask import Flask, request, make_response
app = Flask(__name__)
app.config['DEBUG'] = True
@app.route('/')
def vistors_count():
# Conversion of string to integer
num = int(request.cookies.get('visitors count', 0))
# Getting the key-visitors count value as 0
num = num+1
output = 'You visited this page for '+str(num) + ' times'
resp = make_response(output)
resp.set_cookie('visitors count', str(num))
return resp
@app.route('/get')
def count():
num = request.cookies.get('visitors count')
return num
app.run()
Creating a cookie in flask:
In Flask, creating a cookie is a straightforward process that involves using the set_cookie() method provided by the make_response() function. Here is an example code snippet that demonstrates how to create a cookie in Flask:
from flask import Flask, make_response
app = Flask(__name__)
@app.route('/')
def index():
resp = make_response('Setting a cookie')
resp.set_cookie('my_cookie', 'cookie_value')
return resp
if __name__ == '__main__':
app.run()
In the above example, we import the Flask library and the make_response() function that is used to create a response object. We then define a route for the root URL / and create a response object using the make_response() function with the message “Setting a cookie”.
Next, we call the set_cookie() method on the response object to set the cookie with the name ‘my_cookie’ and value ‘cookie_value’. Finally, we return the response object to the user.
When the user visits the URL, the server will respond with the message “Setting a cookie” and also set a cookie with the name ‘my_cookie’ and value ‘cookie_value’. The browser will then store the cookie and send it back to the server with subsequent requests to that host until the cookie expires or is deleted.
Overall, creating cookies in Flask is a simple process that can be done using the set_cookie() method provided by the make_response() function.
Conclusion
On the client’s computer, cookies are saved as text files. In order to improve visitors ’ experience and website statistics, the goal is to recall and track data pertinent to consumer usage. The cookie’s properties are contained in the Flask Request object. The client is moved, and it is a dictionary object containing all cookie parameters and their respective values.
We utilise cookies to save and track user activity to enhance their experience on the site. They also keep track of details like the site’s domain, route, and expiration date.
Websites like Facebook keep you signed in even after you leave, allowing seamless access on your next visit. You often receive suggestions for various products on eCommerce websites depending on the search history of your browser. Cookies also save information about the website’s domain name, route, and expiration date.
