Django
Dependency injection for Django is available via the provided integration in wireup.integration.django
.
Features:
- Inject dependencies in Django views.
- Supports functions and class-based views.
- Eliminates the need for
@container.autowire
.
- Expose
django.http.HttpRequest
as a wireup dependency.- Available as a
TRANSIENT
scoped dependency, your services can ask for a django request object.
- Available as a
Installation
To install the integration, add wireup.integration.django
to INSTALLED_APPS
, define a new WIREUP
setting and add the wireup middleware.
settings.py
import os
from wireup.integration.django import WireupSettings
INSTALLED_APPS = [
...,
"wireup.integration.django"
]
MIDDLEWARE = ["wireup.integration.django.wireup_middleware"]
WIREUP = WireupSettings(
# This is a list of top-level modules containing service registrations.
# It can be either a list of strings or module types.
service_modules=["mysite.polls.services"]
)
# Additional application settings.
S3_BUCKET_ACCESS_TOKEN = os.environ["S3_BUCKET_ACCESS_TOKEN"]
Usage
Define some services
mysite/polls/services/s3_manager.py
from wireup import service
@service
@dataclass
class S3Manager:
# Reference configuration by name.
# This is the same name this appears in settings.
access_token: Annotated[str, Inject(param="S3_BUCKET_ACCESS_TOKEN")]
def upload(self, file: File) -> None: ...
It is also possible to use django settings in factories.
mysite/polls/services/github_client.py
@dataclass
class GithubClient:
api_key: str
mysite/polls/services/factories.py
from wireup import service
@service
def github_client_factory() -> GithubClient:
return GithubClient(settings.GH_API_KEY)
Inject
To perform injection simply request the dependencies in the view.
app/views.py
def upload_file_view(request: HttpRequest, s3_manager: S3Manager) -> HttpResponse:
return HttpResponse(...)
Class-based views are also supported, you can specify dependencies in your class' __init__
function.
For more examples see the Wireup Django integration tests.
Testing
For general testing tips with Wireup refer to the test docs. With Django you can override dependencies in the container as follows:
test_thing.py
from wireup.integration.django.apps import get_container
def test_override():
class DummyGreeter(GreeterService):
def greet(self, name: str) -> str:
return f"Hi, {name}"
with get_container().override.service(GreeterService, new=DummyGreeter()):
res = self.client.get("/greet?name=Test")