No project description provided
Project description
fastapi-better-di
What is this ?
fastapi-better-di
is a utility that allows you to use DI in fastapi without Depends()
Installation
pip install fastapi_better_di
Examples
# app.py
import uvicorn
from fastapi import FastAPI
from fastapi_better_di.patcher.auto import is_pathed
# functions were patched immediately after import
assert is_pathed(), "Something went wrong"
class MyType:
def __init__(self, value):
self.value = value
app = FastAPI()
app.dependency_overrides[MyType] = lambda: MyType(123)
@app.get("/")
def handler(my_type: MyType): # <- DI without `Depends()`
assert my_type.value == 123
return my_type
if __name__ == "__main__":
uvicorn.run(app)
Usage
- Patching:
-
Auto patching: patches classes when importing:
from fastapi_better_di.patcher.auto import is_pathed # The classes were patched immediately after import # To check if everything is OK, use assert assert is_pathed(), "Something went wrong"
-
Manual patching: you need to call
patch()
by yourself:from fastapi_better_di.patcher.manual import patch, is_pathed patch() # To check if everything is OK, use assert assert is_pathed(), "Something went wrong"
-
-
IMPORTANT: You can still use
= Depends()
without a function as an argument, and it won't add unnecessary arguments to the swagger.- Related issue: fastapi issue
-
IMPORTANT: The main app(
FastAPI
) anddependency_overrides
must be initialized before importing routers!
How it works
fastapi-better-di
simply patch the handler function and add = Depends(func)
as the default argument
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Close
Hashes for fastapi_better_di-0.3.2-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 5961a5308c843adcfc22f8474a525b6403fe3f113052938aa0bb4315b24cb743 |
|
MD5 | b94463a65133ad24180da8bd3d5f56c9 |
|
BLAKE2b-256 | 6f4f1fc1e22a5cd5c8fcc003010b4abf41d473b2f62dee6dc53f68bb4cd859e0 |