Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/uriyyo/fastapi-lifespan-manager
FastAPI LifespanManager 🧑⚖️
https://github.com/uriyyo/fastapi-lifespan-manager
asgi-toolkit fastapi lifespan
Last synced: 3 months ago
JSON representation
FastAPI LifespanManager 🧑⚖️
- Host: GitHub
- URL: https://github.com/uriyyo/fastapi-lifespan-manager
- Owner: uriyyo
- License: mit
- Created: 2023-04-14T15:35:52.000Z (almost 2 years ago)
- Default Branch: main
- Last Pushed: 2024-04-12T03:53:31.000Z (10 months ago)
- Last Synced: 2024-04-12T11:20:06.331Z (10 months ago)
- Topics: asgi-toolkit, fastapi, lifespan
- Language: Python
- Homepage:
- Size: 565 KB
- Stars: 15
- Watchers: 1
- Forks: 1
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
Fastapi LifespanManager`fastapi-lifespan-manager` is a Python library that provides a lifespan manager for FastAPI applications.
The `LifespanManager` in `fastapi-lifespan-manager` allows you to have multiple lifespan in one
application.This library is particularly useful for managing background tasks, such as starting and stopping a database
connection or managing a cache, as well as for performing cleanup tasks, such as closing open file
handles or shutting down running processes.To use `fastapi-lifespan-manager`, simply install it via pip:
```bash
pip install fastapi-lifespan-manager
```Usage Example:
```python
from typing import AsyncIteratorfrom fastapi import FastAPI
from redis.asyncio import Redis
from sqlalchemy.ext.asyncio import create_async_enginefrom fastapi_lifespan_manager import LifespanManager, State
manager = LifespanManager()
@manager.add
async def setup_db(app: FastAPI) -> AsyncIterator[State]:
engine = await create_async_engine("postgresql+asyncpg://user:password@localhost/db")yield {"db": engine}
await engine.dispose()
@manager.add
async def setup_cache(app: FastAPI) -> AsyncIterator[State]:
redis = await Redis.from_url("redis://localhost:6379/0")yield {"cache": redis}
await redis.close()
await redis.wait_closed()app = FastAPI(lifespan=manager)
```