from fastapi import Depends, FastAPI
class MyDependency:
def __init__(self):
# Perform initialization logic here
pass
def some_method(self):
# Perform some operation
pass
def get_dependency():
# Create and return an instance of the dependency
return MyDependency()
app = FastAPI()
@app.get("/example")
def example(dependency: MyDependency = Depends(get_dependency)):
dependency.some_method()
For the code snippet above, does subsequent visits to /example create a new instance of the MyDependency object each time? If so, how can I avoid that?
Yes, each request will receive a new instance.
If you don't want that to happen, use a cache decorator, such as the built-in lru_cache in functools: - it's just a regular function, so any decorators will still be invoked (since they replace the original function with a new one which wraps the old one):
from functools import lru_cache
...
@lru_cache
def get_dependency():
# Create and return an instance of the dependency
return MyDependency()
However, if you use the same dependency multiple places in the hiearchy (for the same request), the same value will be re-used.
If one of your dependencies is declared multiple times for the same path operation, for example, multiple dependencies have a common sub-dependency, FastAPI will know to call that sub-dependency only once per request.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With