fastapi-events icon indicating copy to clipboard operation
fastapi-events copied to clipboard

Trigger an event at startup

Open ACassimiro opened this issue 2 years ago • 0 comments

Is there a way to trigger an event at the startup of the application? I've been trying to do so with variations of the following piece of code:

app = FastAPI()
app.add_middleware(EventHandlerASGIMiddleware, 
                  handlers=[local_handler])
app.include_router(example.router)

@app.on_event("startup")
async def startup_event():
   dispatch("STARTING")

And I'm getting this error at the application startup:

ERROR:    Traceback (most recent call last):
  File "/home/acassimiro/Documents/tools/fastapi/eventDrivenApp/env/lib/python3.8/site-packages/starlette/routing.py", line 635, in lifespan
    async with self.lifespan_context(app):
  File "/home/acassimiro/Documents/tools/fastapi/eventDrivenApp/env/lib/python3.8/site-packages/starlette/routing.py", line 530, in __aenter__
    await self._router.startup()
  File "/home/acassimiro/Documents/tools/fastapi/eventDrivenApp/env/lib/python3.8/site-packages/starlette/routing.py", line 612, in startup
    await handler()
  File "/home/acassimiro/Documents/tools/fastapi/eventDrivenApp/main.py", line 39, in startup_event
    dispatch("STARTING")
  File "/home/acassimiro/Documents/tools/fastapi/eventDrivenApp/env/lib/python3.8/site-packages/fastapi_events/dispatcher.py", line 94, in dispatch
    return _dispatch(event_name=event_name, payload=payload)
  File "/home/acassimiro/Documents/tools/fastapi/eventDrivenApp/env/lib/python3.8/site-packages/fastapi_events/dispatcher.py", line 61, in _dispatch
    _dispatch_as_task(event_name, payload)
  File "/home/acassimiro/Documents/tools/fastapi/eventDrivenApp/env/lib/python3.8/site-packages/fastapi_events/dispatcher.py", line 37, in _dispatch_as_task
    handlers = _list_handlers()
  File "/home/acassimiro/Documents/tools/fastapi/eventDrivenApp/env/lib/python3.8/site-packages/fastapi_events/dispatcher.py", line 28, in _list_handlers
    middleware_id: int = middleware_identifier.get()
LookupError: <ContextVar name='fastapi_middleware_identifier' at 0x7fdbec69dd60>

ERROR:    Application startup failed. Exiting.

The task that I want to run with this starting event is supposed to dispatch events periodically, so even if I initially run it as a background task, I get the same error sometime after the application finishes starting. My current workaround is to manually call an endpoint that dispatches this event once the application is up and running, but I'd like to get rid of this step.

By the way, thanks for the effort and work in this project.

ACassimiro avatar Aug 01 '22 14:08 ACassimiro