To manage asynchronous PostgreSQL database connections in a FastAPI application using the lifespan event, you can follow these steps. This approach ensures efficient connection pooling and proper resource cleanup.
Steps to Set Up Async PostgreSQL Connections with Lifespan
1. Install Dependencies
Ensure you have the necessary libraries installed:
pip install fastapi psycopg[pool] uvicorn
2. Define the Connection Pool
Use psycopg's AsyncConnectionPool to manage database connections efficiently:
from psycopg_pool import AsyncConnectionPool
DATABASE_URL = "postgres://user:password@localhost/dbname"
# Initialize the connection pool
pool = AsyncConnectionPool(DATABASE_URL, open=False)
3. Set Up the Lifespan Event
The lifespan event in FastAPI allows you to initialize and clean up resources when the application starts and stops:
from fastapi import FastAPI
from contextlib import asynccontextmanager
@asynccontextmanager
async def lifespan(app: FastAPI):
# Open the connection pool at startup
await pool.open()
yield
# Close the connection pool at shutdown
await pool.close()
app = FastAPI(lifespan=lifespan)
4. Create a Dependency for Database Connections
Define a dependency to provide a database connection for each request:
from fastapi import Depends
async def get_db_connection():
async with pool.connection() as conn:
yield conn
5. Use the Dependency in Endpoints
Inject the database connection into your route handlers using Depends:
@app.get("/items/")
async def read_items(conn=Depends(get_db_connection)):
async with conn.cursor() as cursor:
await cursor.execute("SELECT * FROM items")
items = await cursor.fetchall()
return {"items": items}
6. Run the Application
Start the FastAPI application with Uvicorn:
uvicorn main:app --reload
Key Considerations
Connection Pooling: Using a connection pool reduces the overhead of repeatedly opening and closing database connections.
Resource Cleanup: The lifespan event ensures that the connection pool is properly closed when the application shuts down.
Concurrency: The asynchronous nature of psycopg and FastAPI allows handling multiple requests efficiently.
This setup is suitable for production-grade applications, ensuring optimal performance and resource management.