Closed arunkumar-pt closed 10 months 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)
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?