Skip to main content

FastAPI Lifespan Manager

Project description

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:

pip install fastapi-lifespan-manager

Usage Example:

from typing import AsyncIterator

from fastapi import FastAPI
from redis.asyncio import Redis
from sqlalchemy.ext.asyncio import create_async_engine

from 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)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastapi_lifespan_manager-0.1.4.tar.gz (4.4 kB view hashes)

Uploaded Source

Built Distribution

fastapi_lifespan_manager-0.1.4-py3-none-any.whl (4.8 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page