Skip to content

How to pass arbitrary data to context #1034

Closed

Description

@cirezd

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:

from fastapi import FastAPI

app = FastAPI()

app.state.custom_context = {"a": "b"}

# In separate file

router = Router()

@router.get("/items/{item_id}")
async def read_items(item_id: str, request: Request):
    example_context = request.app.state.custom_context
    return items[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?

Any guidance would be helpful. Thanks!

Activity

  1. added
    t-tooling
    on Feb 27, 2025
  2. Mantisus commented on Feb 27, 2025

    @Mantisus
    Collaborator

    Hey @cirezd.

    Thank you for your interest! Take a look at use_state, I think that's what you're looking for

  3. cirezd commented on Mar 1, 2025

    @cirezd
    Author

    Thank you. I am not sure it covers the same use case, but it seems more appropriate than user_data.

  4. vdusek commented on Mar 3, 2025

    @vdusek
    Collaborator

    Hi @cirezd, as was mentioned, you can use either either Request.user_data or context.use_state.

  5. locked and limited conversation to collaborators on Mar 3, 2025
  6. converted this issue into a discussion #1043 on Mar 3, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    t-tooling

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions