You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Hello, I am looking for a way to inject or pass arbitrary data to the context object. Similar to what is possible in fastapi via app.state or via dependencies:
fromfastapiimportFastAPIapp=FastAPI()
app.state.custom_context= {"a": "b"}
# In separate filerouter=Router()
@router.get("/items/{item_id}")asyncdefread_items(item_id: str, request: Request):
example_context=request.app.state.custom_contextreturnitems[item_id]
My use case is that I have the handlers in separate files and I would like to pass general run information to the handlers, without the need for database requests. I am aware of user_data, but I am not sure this is appropriate here, since it is more tied to the Request and not the overall run. Furthermore, I don't see a straight-forward way to pass the data from the start_urls? Is it possible to abuse the pre_navigation_hook or something similar?
Activity
Mantisus commentedon Feb 27, 2025
Hey @cirezd.
Thank you for your interest! Take a look at
use_state, I think that's what you're looking forcirezd commentedon Mar 1, 2025
Thank you. I am not sure it covers the same use case, but it seems more appropriate than user_data.
vdusek commentedon Mar 3, 2025
Hi @cirezd, as was mentioned, you can use either either
Request.user_dataorcontext.use_state.