Welcome to the Flask Cookies tutorial! In this lesson, we'll learn how to work with cookies in Flask applications. Cookies are small pieces of data stored on the client side (browser) by the server, allowing us to maintain state between multiple requests 💡.
Cookies are text files created by a web server and stored on the client's computer. They contain information such as user preferences, login information, and session data. When a client accesses a website, the browser sends the cookies back to the server with each request.
First, let's create a simple Flask application to set a cookie:
from flask import Flask, make_response, jsonify
app = Flask(__name__)
@app.route('/setcookie')
def set_cookie():
response = make_response('Cookie set successfully!')
response.set_cookie('username', 'JohnDoe', expires=3600) 💡 _expires sets the cookie expiration (in seconds)
return responseNext, let's create a route to get the cookie we set:
@app.route('/getcookie')
def get_cookie():
username = request.cookies.get('username') 📝 _request.cookies is a Flask object that allows you to access the cookies sent by the client
return jsonify({'username': username})Securing cookies is crucial to protect user data. Here's an example of setting a secure cookie in Flask:
from flask import Flask, make_response, jsonify, secrets
app = Flask(__name__)
SECRET_KEY = secrets.token_hex(16) 📝 _secrets.token_hex generates a random secret key
@app.route('/setcookie')
def set_cookie():
response = make_response('Cookie set successfully!')
response.set_cookie('username', 'JohnDoe', expires=3600, secure=True, samesite='Strict') 💡 _secure=True sets the cookie as secure (transmitted only over HTTPS), and samesite='Strict' sets the SameSite cookie policy to Strict
return responseIn this example, the cookie is set with the secure=True and samesite='Strict' options, making it secure against cross-site scripting attacks.
That's it for this lesson on Flask Cookies! In the next tutorial, we'll dive into Flask Sessions 🚀. Happy coding! 🎉