Flash Cookies
0 413
Introduction to Cookies in Flask
Cookies are small pieces of data stored on the client’s browser that help web applications remember information about users across multiple requests. In Flask, working with cookies is simple and allows you to create personalized and stateful user experiences.
How to Set Cookies in Flask
To set a cookie in Flask, you need to create a response object and then use the set_cookie method to add the cookie to the response. You can also specify properties such as expiration time, security flags, and scope.
from flask import Flask, make_response
app = Flask(__name__)
@app.route('/setcookie')
def setcookie():
response = make_response("Cookie is set")
response.set_cookie('username', 'JohnDoe', max_age=60*60*24) # Expires after 1 day
return response
Accessing Cookies in Flask
Retrieving cookie data in Flask is done via the request.cookies object. You can access a cookie by its name and provide a default value if the cookie does not exist.
from flask import request
@app.route('/getcookie')
def getcookie():
username = request.cookies.get('username', 'Guest')
return f"Hello, {username}!"
Practical Use: Login with Cookies
Cookies are commonly used to keep track of logged-in users. For example, after a user submits their username via a form, you can store it in a cookie and greet them on subsequent visits:
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
response = make_response(f"Welcome, {username}!")
response.set_cookie('username', username)
return response
return '''
<form method="post">
Username: <input type="text" name="username">
<input type="submit" value="Login">
</form>
'''
Security Tips for Using Cookies
- Set
httponly=Trueto prevent JavaScript access and reduce cross-site scripting risks. - Use
secure=Trueto ensure cookies are sent only over HTTPS connections. - Limit the cookie’s scope using
pathanddomainparameters. - Avoid storing sensitive data directly in cookies; prefer server-side sessions instead.
Deleting Cookies
To remove a cookie, set its expiration date in the past or use the delete_cookie method:
@app.route('/logout')
def logout():
response = make_response("Logged out successfully")
response.set_cookie('username', '', expires=0)
return response
Summary
Flask’s cookie handling is straightforward and useful for persisting small amounts of user-specific data on the client side. By setting, reading, and deleting cookies properly, and following security best practices, you can create personalized, secure web applications easily.
If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!
Share:



Comments
Waiting for your comments