What Are Sessions and Cookies?
- Session: A session is a mechanism to store user-specific data (like authentication status) between requests. It allows the server to “remember” users as they interact with the application.
- Cookie: A small piece of data stored in the client’s browser. In this tutorial, we’ll use cookies to store session IDs, which the server uses to fetch session details from Redis.
Why Redis?
Redis is a great choice for session management because:- Fast Lookups: Redis is an in-memory database, ensuring near-instantaneous access to session data.
- Expiration Control: Built-in expiration functionality allows sessions to automatically expire after a defined timeout.
Setup
1. Install the Required Libraries
Install FastAPI, Upstash Redis, and other necessary dependencies:2. Create a Redis Database
Create a Redis database using the Upstash Console or Upstash CLI. Create a.env
file in the root of your project with the following content:
Code
Let’s implement a simple FastAPI application that handles login, profile access, and logout using Redis for session management. We use sliding expiration by updating the session expiration time on every request. If a session is inactive for 15 minutes (900 seconds), it will automatically expire.main.py
test_script.py
Code Explanation
-
/login/
Endpoint:- Generates a unique session ID using
uuid.uuid4()
. - Stores the session data in Redis using the session ID as the key.
- Sets a cookie named
session_id
with the generated session ID. - Returns a success message along with the session ID.
- Generates a unique session ID using
-
/profile/
Endpoint:- Retrieves the session ID from the cookie.
- Fetches the session data from Redis using the session ID.
- Updates the session expiration time.
- Returns the session ID and session data.
-
/logout/
Endpoint:- Deletes the session data from Redis using the session ID.
- Clears the
session_id
cookie.
Run the Application
-
Start the FastAPI server:
-
Run the test script: