Manage Sessions in Python with Serverless Redis
In this tutorial, we’ll see how to implement session management in a FastAPI application using Upstash Redis. We’ll use cookies to store session IDs, while session data is maintained in Redis for its speed and expiration features.
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.
Let’s test the implementation using the following script:
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:
Here’s what you should expect:
Conclusion
By combining FastAPI, cookies, and Upstash Redis, we’ve created a reliable session management system. With Redis’s speed and built-in expiration features, this approach ensures secure and efficient handling of user sessions.
To learn more about Upstash Redis, visit the Upstash Redis Documentation.