Flask Tutorials: Cookies (get and set) 🎉

beginner
22 min

Flask Tutorials: Cookies (get and set) 🎉

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 💡.

What are Cookies? 🎯

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.

Why Use Cookies? 📝

  1. Session Management: Cookies help maintain user sessions by storing session IDs.
  2. Personalization: Cookies can store user preferences, like language or theme, to enhance the user experience.
  3. Authentication: Cookies can store login credentials for secure access to the user's account.

Setting Cookies in Flask 🎯

First, let's create a simple Flask application to set a cookie:

python
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 response

Getting Cookies in Flask 🎯

Next, let's create a route to get the cookie we set:

python
@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})

Quiz 📝

Advanced Example: Secure Cookies 💡

Securing cookies is crucial to protect user data. Here's an example of setting a secure cookie in Flask:

python
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 response

In 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! 🎉