In this blog post, we'll walk you through the process of getting and setting cookies in a Flask application with step-by-step examples. Cookies are small pieces of data stored on the client-side and are essential for managing user sessions and preferences in web applications. Flask, a lightweight WSGI web application framework in Python, provides simple methods to work with cookies.
Setting Up Your Flask Environment
Before we dive into cookies, ensure you have Flask installed.
pip install Flask
from flask import Flask, request, make_response
app = Flask(__name__)
@app.route('/')
def index():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True)
Run the application by executing:
python app.py
Your Flask app should now be running on `http://127.0.0.1:5000/`.
- Unlocking the Power of Free Google Tools for Seo Success
- Ultimate Guide: Google Search Console Crawl Reports you need to know Monitor
- What is dofollow backlinks: The ultimate 5 Benefit for your websites SEO
- Schema markup and How can you use schema markup for seo
Setting Cookies
To set a cookie in Flask, you need to create a response object and use its `set_cookie` method. Here's how you can do it:
Create a route to set a cookie
@app.route('/setcookie')
def set_cookie():
response = make_response('Cookie is set')
response.set_cookie('username', 'daily aspirants')
return response
Test setting the cookie
Getting Cookies
Retrieving cookies is straightforward with Flask. You can access cookies using the `request` object's `cookies` attribute.
Create a route to get the cookie
@app.route('/getcookie')
def get_cookie():
username = request.cookies.get('username')
if username:
return f'Username stored in cookie is {username}'
else:
return 'No username cookie found'
Test getting the cookie:
Deleting Cookies
Sometimes, you might need to delete a cookie. You can achieve this by setting the cookie's expiration date to a time in the past.
Create a route to delete the cookie
@app.route('/deletecookie')
def delete_cookie():
response = make_response('Cookie has been deleted')
response.set_cookie('username', '', expires=0)
return response
Test deleting the cookie:
Here's a summary of the code we used:
from flask import Flask, request, make_response
app = Flask(__name__)
@app.route('/')
def index():
return 'Hello, World!'
@app.route('/setcookie')
def set_cookie():
response = make_response('Cookie is set')
response.set_cookie('username', 'daily aspirants')
return response
@app.route('/getcookie')
def get_cookie():
username = request.cookies.get('username')
if username:
return f'Username stored in cookie is {username}'
else:
return 'No username cookie found'
@app.route('/deletecookie')
def delete_cookie():
response = make_response('Cookie has been deleted')
response.set_cookie('username', '', expires=0)
return response
if __name__ == '__main__':
app.run(debug=True)
Now, create a `templates` directory and add the following HTML files for the respective routes:
'templates/index.html'
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Flask Cookie Demo</title>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-5">
<h1>Welcome to the Flask Cookie Demo</h1>
<p>
{% if request.cookies.get('username') %}
Hello, {{ request.cookies.get('username') }}! <a href="{{ url_for('logout') }}" class="btn btn-primary">Logout</a>
{% else %}
You are not logged in. <a href="{{ url_for('login') }}" class="btn btn-primary">Login</a>
{% endif %}
</p>
</div>
</body>
</html>
'templates/login.html'
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Login</title>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-5">
<h1>Login</h1>
<form method="post">
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" id="username" name="username" required>
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
</body>
</html>
templates/readcookies.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Read Cookies</title>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-5">
<h1>Read Cookies</h1>
<p>
{% if username %}
Username stored in cookie is {{ username }}.
{% else %}
No username cookie found.
{% endif %}
</p>
<a href="{{ url_for('index') }}" class="btn btn-primary">Back to Home</a>
</div>
</body>
</html>
app.py
from flask import Flask, request, make_response, render_template, redirect, url_for
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
response = make_response(redirect(url_for('index')))
response.set_cookie('username', username)
return response
return render_template('login.html')
@app.route('/logout')
def logout():
response = make_response(redirect(url_for('index')))
response.set_cookie('username', '', expires=0)
return response
@app.route('/readcookies')
def read_cookies():
username = request.cookies.get('username')
return render_template('readcookies.html', username=username)
if __name__ == '__main__':
app.run(debug=True)
Conclusion
In this tutorial, we've covered the basics of setting, getting, and deleting cookies in a Flask application. Cookies are crucial for maintaining state and personalizing user experiences. By leveraging Flask's simple and intuitive methods, you can effectively manage cookies in your web applications.