jeudi 26 août 2021

What is the best practice for Dependency Injection in Django/Python?

I work on a Django-based product that works as a proxy between an enterprise ERP and some mobile clients. So it supposes to have scalability and easy maintenance in long run.

One challenge I'm facing right now is the ability to have multiple versions both on API I expose to clients, and also API I consume from the ERP.

I have my business logic in a separate module in each app named *_usecase.py, essentially I should implement versioning by having a base UseCase class and override methods for each version and provide the right class instance to view through DI based on request/response header values.

So I've reached this package python-inject. It has pretty neat decorators to inject instances based on configuration you have and type annotation for method parameters. something like:

# in view.py
@inject.autoparams()
def send_notification(
    request, 
    use_case: SendNotificationUseCase, 
    # as many type annotated parameters you required
):
    pass

# in binder.py
class AppNameBinder(BaseBinder):
    def __call__(self, binder, *args, **kwargs):
        binder.bind_to_provider(
            SendNotificationUseCase, 
            self.provide_send_notification_use_case
        )
    def provide_send_notification_use_case(self):
            # some check and logic to evaluate appropriate version
            return SendNotificationUseCaseV1() # v1 implementation of usecase

So this package does the job eventually, although I had some minor issues with it here and there but, since it doesn't have that many stars and I haven't seen its usage anywhere in the community, I want to know if you guys have better/more pythonic solution for Dependency Injection in Django/Python and also for this versioning challenge I mentioned.

Aucun commentaire:

Enregistrer un commentaire