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
As the author of the anydi library, which has been primarily used with FastAPI, I've decided to use Django Ninja for my next project and integrate it with anydi. I want to share how to use them in combination and point out some implementation details which might seem a bit 'patchy'.
Add anydi.ext.django to the bottom of your INSTALLED_APPS in settings.py:
INSTALLED_APPS= [
...
'anydi.ext.django',
]
Configure the ANYDI settings in settings.py:
ANYDI= {
"PATCH_NINJA": True,
}
This setting patches Django Ninja to use anydi for dependency injection. The implementation involves replacing the Operation and AsyncOperation classes with custom ones that resolve dependencies using anydi. The details of this can be found here: anydi integration for Django Ninja. I welcome any advice on how to improve this.
Assume you have a service that you want to inject:
classUserService:
defcreate_user(self, email: str, password: str) ->User:
# Business logic can be much more complex ;)returnUser.objects.create_user(email=email, password=password)
You can now inject the service directly into your endpoint:
As the author of the
anydi
library, which has been primarily used withFastAPI
, I've decided to useDjango Ninja
for my next project and integrate it withanydi
. I want to share how to use them in combination and point out some implementation details which might seem a bit 'patchy'.https://anydi.readthedocs.io/en/stable/extensions/django/
Here is a quick guide on how to set this up:
First, install the anydi library:
Add
anydi.ext.django
to the bottom of yourINSTALLED_APPS
insettings.py
:Configure the
ANYDI
settings insettings.py
:This setting patches
Django Ninja
to useanydi
for dependency injection. The implementation involves replacing theOperation
andAsyncOperation
classes with custom ones that resolve dependencies usinganydi
. The details of this can be found here: anydi integration for Django Ninja. I welcome any advice on how to improve this.Assume you have a service that you want to inject:
You can now inject the service directly into your endpoint:
Using modules
myapp/users/module.py
Register
UsersModule
insettings.py
You can also use all the features of
anydi
withDjango Ninja
, including scopes, named dependencies, modules, async support, etc.For more details, please check out the
anydi
documentation: anydi Documentation.The text was updated successfully, but these errors were encountered: