Integrate injector with Django
Django injector is an app for Django that integrates injector with Django.
Injector is a simple and easy to use dependency injection framework.
$ pip install django_injector
MIDDLEWARE in your Django configuration.
django_injector uses the module mechanism from injector. Desired modules should be
listed in the
INJECTOR_MODULES setting, each item must be either a subclass of
or a callable that can receive a binder as its only argument.
Modules are loaded when the app is loaded.
To use the injector decorate functions or methods with
methods or functions can receive additional, non-injected, arguments, they should be listed
before injected arguments.
This is an example of a view function that receives a
request from Django and
an injected argument.
from django_injector import inject from my_app.services import SomeService @inject def my_view(request, some_service: SomeService): """Will receive a `request` from Django and `some_service` from the injector.""" return some_service.do_something(request)
A custom Injector scope is provided – it's the request scope. Types bound in the request scope share instances during handling a single request but don't cross request handling boundary. It's similar to Flask-Injector's request scope.
The request scope depends on only single request being handled by a single thread (green threads, when gevent or Eventlet monkey patching is used, are also supported) at a time.
from django_injector import request_scope from django_injector import inject class Service: pass class RequiresService: @inject def __init__(self, service: Service): self.service = service class AlsoRequiresService: @inject def __init__(self, service: Service): self.service = service @inject def my_view(request, service: Service, rs: RequiresService, ars: AlsoRequiresService): # The same Service instance everywhere assert service is rs.service assert rs.service is ars.service # ...
One can inject
django.http.HttpRequest and it'll be the same object as the
request argument inside
the views. The binding can be used to provide
HttpRequest deep in the object hierarchy without
having to pass it manually.
from django.http import HttpRequest from django_injector import inject class RequiresRequest: @inject def __init__(self, request: HttpRequest): self.request = request @inject def my_view(request, rr: RequiresRequest): # The same request everywhere assert rr.request is request # ...
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
|Filename, size||File type||Python version||Upload date||Hashes|
|Filename, size django_injector-0.1.1-py3-none-any.whl (9.7 kB)||File type Wheel||Python version py3||Upload date||Hashes View|
|Filename, size django_injector-0.1.1.tar.gz (5.6 kB)||File type Source||Python version None||Upload date||Hashes View|
Hashes for django_injector-0.1.1-py3-none-any.whl