Will instances of injected dependencies be reused when depended upon multiple times? #11332
-
First Check
Commit to Help
Example Codefrom fastapi import FastAPI, Depends
app = FastAPI()
# Assuming this is your Context class
class Context:
def __init__(self, auth_info: str):
self.auth_info = auth_info
# Initialize your database connection here
# Your BatchProcessor class that depends on Context
class BatchProcessor:
def __init__(self, context: Context):
self.context = context
# Use context to access db connection, auth info, etc.
# Dependency that produces a Context object
def get_context() -> Context:
# Create and return a Context instance
# For example, auth_info could come from request headers
return Context(auth_info="User XYZ")
# Dependency that produces a BatchProcessor object, depends on Context
def get_batch_processor(context: Context = Depends(get_context)) -> BatchProcessor:
return BatchProcessor(context=context)
# An endpoint that depends on both Context and BatchProcessor
@app.get("/my_endpoint")
async def my_endpoint(context: Context = Depends(get_context),
batch_processor: BatchProcessor = Depends(get_batch_processor)):
# Here, you can use both context and batch_processor as needed
return {"message": "Using both Context and BatchProcessor"}DescriptionI am using Depends for the first time and so far it was good to me. However I stumble a little in edge cases. Let me present the sample code; I have 2 dependencies
Every endpoint that depends on Every endpoint basically need access to the context directly, even if it also needs access to batch_processor. And here is the question: Will the context that my endpoint gains access to in the example code be the same instance as the one provided to BatchProcessor, or will I have two distict instances of this class? How can I understand why/how (how does FastAPI do this under the hood)? I looked at the official documentation trying to learn about this, but it is on a much shallower level. Operating SystemLinux Operating System DetailsNot relevant FastAPI Version0.103.2 Pydantic Version2.4.0 Python Version3.9.2 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
|
Yes, in your case the result of To test that you can add You can also add debug print to the |
Beta Was this translation helpful? Give feedback.
Yes, in your case the result of
get_contextwill be cached and it will be the same object during one endpoint call.Doc: https://fastapi.tiangolo.com/tutorial/dependencies/sub-dependencies/#using-the-same-dependency-multiple-times
To test that you can add
assert context == batch_processor.contextto your endpoint code: