airtai / faststream

FastStream is a powerful and easy-to-use Python framework for building asynchronous services interacting with event streams such as Apache Kafka, RabbitMQ, NATS and Redis.
https://faststream.airt.ai/latest/
Apache License 2.0
2.2k stars 106 forks source link

[Question] How can we integrate Fastkafka with Fastapi when we already have bunch of lifespan methods? #358

Closed arunkumar-pt closed 10 months ago

arunkumar-pt commented 1 year ago

I have a Fastapi application with a bunch of lifespan methods, like starting db, Redis, etc. I would like to add Fastkafka to the fastapi application along with already existing lifespan methods. Could you pls guide me on how to do it?

sternakt commented 1 year ago

Simplest solution I can think of right now is: When you call kafka_lifespan = kafka_app.fastapi_lifespan(kafka_broker_name="localhost") the returning object is an async context manager that you can pass to your FastAPI app If you already have a lifespan defined, you could use async with kafka_lifespan inside your FastAPI lifespan to enter the FastKafka lifespan context along with your already existing lifespan methods.

In code this would look like this:

kafka_app = FastKafka(...)
# create FastKafka lifespan for FastAPI
kafka_lifespan = kafka_app.fastapi_lifespan(kafka_broker_name="localhost")

@asynccontextmanager
async def lifespan(app: FastAPI):
    # starting db, Redis, etc.
    # Add FastKafka lifespan to existing FastAPI lifespan
    async with kafka_lifespan:
        yield
    # Your cleanup

app = FastAPI(lifespan=lifespan)