Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: support lifespan state in FastStream – FastAPI integration #2132

Open
Lancetnik opened this issue Mar 17, 2025 · 3 comments
Open
Labels
enhancement New feature or request

Comments

@Lancetnik
Copy link
Member

Lancetnik commented Mar 17, 2025

Well, we missed ASGI State feature – https://www.starlette.io/lifespan/

The following code should works without errors

from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from faststream.nats.fastapi import NatsRouter

@asynccontextmanager
async def lifespan(app: FastAPI):
    yield {"data": 1}

app = FastAPI(lifespan=lifespan)
router = NatsRouter()
app.include_router(router)

@router.subscriber("test")
async def handler(request: Request):
    assert request.state.data == 1

@router.after_startup
async def _(app: FastAPI):
    await router.broker.publish("Hi!", "test")

But, it couldn't be implemented in a regular way. Originally, ASGI server stores yielded values and injects it in each HTTP request – https://asgi.readthedocs.io/en/latest/specs/lifespan.html#lifespan-state

But, there is ni HTTP request and ASGI server on router.subscriber call, so we should inject this state manually.

We should pass this maybe_statehttps://github.com/airtai/faststream/blob/main/faststream/broker/fastapi/router.py#L315

To request object – somewhere here https://github.com/airtai/faststream/blob/main/faststream/broker/fastapi/route.py#L210

@Lancetnik Lancetnik added the enhancement New feature or request label Mar 17, 2025
@Lancetnik Lancetnik added the good first issue Good for newcomers label Mar 17, 2025
@Lancetnik Lancetnik moved this to Backlog in FastStream Mar 17, 2025
@RenameMe1
Copy link
Contributor

Can i work on this issue?

@Lancetnik
Copy link
Member Author

Can i work on this issue?

For sure, thank you!

@Lancetnik
Copy link
Member Author

Well, seems like it's not so easy. We can't get FastAPI.lifespan_context inside our router.lifespan method. We should figure it out before implement this feature

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
Status: Backlog
Development

No branches or pull requests

2 participants