类似于main.py的Django应用程序的入口点是什么?在哪里设置参数?

What is the entry point of a Django app similar to main.py? Where do I set up parameters?

我想设置一些参数并初始化 Injector 对象,因为我想在我的 Django 应用程序中使用依赖注入和单例。

通常我在我的应用程序的 main.py 中这样做,但是对于 Django,我看不到应用程序运行时的第一个入口点在哪里。我应该在哪里初始化注入器并向它传递我的视图和服务?

我有这样的看法:

from uuid import UUID
from django.shortcuts import render
from django.http.response import JsonResponse
from django.http.request import HttpRequest
from rest_framework import viewsets, status
from rest_framework.parsers import JSONParser
from rest_framework.response import Response
from Instruments.services import InstrumentsService
from rest_framework.decorators import api_view
from Instruments.services import InstrumentsService
from injector import singleton, inject


# Application views live here
@singleton
class InstrumentViewSet(viewsets.ModelViewSet):
    @inject
    def __init__(self, instrument_service: InstrumentsService, **kwargs):
        self.instrument_service = instrument_service
        super().__init__(**kwargs)

    def list(self, request: HttpRequest):
        data = {}

        try:
            data = self.instrument_service.get_instruments()
            return JsonResponse(data, status=status.HTTP_200_OK, safe=False)
        except Exception as exc:
            return JsonResponse(
                {"Status": f"Error: {exc}"},
                status=status.HTTP_400_BAD_REQUEST,
                safe=False,
            )

    def create(self, request):
        instrument_data = JSONParser().parse(request)
        data = {}

        try:
            data = self.instrument_service.add_instrument(instrument_data)
            return JsonResponse(data, status=status.HTTP_201_CREATED, safe=False)
        except Exception as exc:
            return JsonResponse(data, status=status.HTTP_400_BAD_REQUEST, safe=False)

    def retrieve(self, request, pk: UUID = None):
        data = {}

        try:
            data = self.instrument_service.get_instrument_by_id(pk)
            return JsonResponse(data, status=status.HTTP_200_OK, safe=False)
        except Exception as exc:
            return JsonResponse(
                {"Status": f"Error: {exc}"},
                status=status.HTTP_404_NOT_FOUND,
                safe=False,
            )

    def update(self, request, pk: UUID = None):
        instrument_data = JSONParser().parse(request)
        data = {}

        try:
            data = self.instrument_service.update_instrument_by_id(pk, instrument_data)
            return JsonResponse(data, status=status.HTTP_200_OK, safe=False)
        except Exception as exc:
            return JsonResponse(
                {"Status": f"Error: {exc}"},
                status=status.HTTP_404_NOT_FOUND,
                safe=False,
            )

    def destroy(self, request, pk: UUID = None):
        data = {}
        try:
            data = self.instrument_service.delete_instrument_by_id(pk)
            return JsonResponse(data, status=status.HTTP_200_OK, safe=False)
        except Exception as exc:
            return JsonResponse(
                {"Status": f"Error: {exc}"},
                status=status.HTTP_404_NOT_FOUND,
                safe=False,
            )

和这样的服务:

import uuid
from django.http.response import JsonResponse
from django.http.request import RAISE_ERROR, HttpRequest
from rest_framework.exceptions import NotFound, ValidationError
from rest_framework.parsers import JSONParser
from rest_framework import status
from Instruments.models import Instrument
from Instruments.serializers import InstrumentsSerializer
from django.shortcuts import get_object_or_404
from injector import inject, singleton


@singleton
class InstrumentsService:
    @inject
    def __init__(self, instruments: Instrument):
        self.instruments = instruments.objects.all()

    def get_instrument_by_id(self, id: uuid.UUID):
        try:
            instruments = get_object_or_404(self.instruments, pk=id)
            serializer = InstrumentsSerializer(instruments)

        except Instrument.DoesNotExist as exc:
            raise NotFound(f"No items where found with the given id {id}")

        return serializer.data

    def update_instrument_by_id(self, id: uuid.UUID, instrument_data: dict):
        try:

            instruments = get_object_or_404(self.instruments, pk=id)
            serializer = InstrumentsSerializer(instruments, data=instrument_data)

            if serializer.is_valid():
                serializer.save()

            else:
                raise ValidationError(
                    "The data provided for updating an instrument are not valid"
                )

        except Instrument.DoesNotExist as exc:
            raise NotFound(f"No items where found with the given id {id}")

        self.instruments = Instrument.objects.all()
        return serializer.data

    def delete_instrument_by_id(self, id: uuid.UUID):
        try:

            instruments = get_object_or_404(self.instruments, pk=id)
            serializer = InstrumentsSerializer(instruments)
            instruments.delete()

        except Instrument.DoesNotExist as exc:
            raise NotFound(f"No items where found with the given id {id}")

        self.instruments = Instrument.objects.all()
        return serializer.data

    def get_instruments(self):
        serializer = InstrumentsSerializer(self.instruments, many=True)

        return serializer.data

    def add_instrument(self, instrument_data: Instrument):

        serializer = InstrumentsSerializer(data=instrument_data)

        if serializer.is_valid():
            serializer.save()
        else:
            raise ValidationError(
                "The data provided for registering a new instrument are not valid"
            )

        self.instruments = Instrument.objects.all()
        return serializer.data

有人会在哪里初始化注入器来创建依赖项?

也许你可以看看Django Applications

在您的应用程序文件夹中,您可能有一个 apps.py 文件:

from django.apps import AppConfig

class MyApp(AppConfig):

    def ready(self):
        # do stuff here

这是您的应用程序的入口点。

编辑:

有一个项目已经这样做了:django-injector

好的,我让依赖注入工作了,问题不在于注入器,而是在上面发布的 class InstrumentsService: 中我试图做的事实:

def __init__(self, instruments: Instrument):
    self.instruments = instruments.objects.all()

但是对象管理器不能通过对象(类实例)访问 Django 对象,而是直接通过 class。因此,如果我将 class InstrumentsService: 更正为这个并使用此 django-injector 模块 Django injector 一切正常:

import uuid
from django.http.response import JsonResponse
from django.http.request import RAISE_ERROR, HttpRequest
from rest_framework.exceptions import NotFound, ValidationError
from rest_framework.parsers import JSONParser
from rest_framework import status
from Instruments.models import Instrument
from Instruments.serializers import InstrumentsSerializer
from django.shortcuts import get_object_or_404


class InstrumentsService:
    def __init__(self):
        self.instruments = Instrument.objects.all()

    def get_instrument_by_id(self, id: uuid.UUID):
        try:
            instruments = get_object_or_404(self.instruments, pk=id)
            serializer = InstrumentsSerializer(instruments)

        except Instrument.DoesNotExist as exc:
            raise NotFound(f"No items where found with the given id {id}")

        return serializer.data

    def update_instrument_by_id(self, id: uuid.UUID, instrument_data: dict):
        try:

            instruments = get_object_or_404(self.instruments, pk=id)
            serializer = InstrumentsSerializer(instruments, data=instrument_data)

            if serializer.is_valid():
                serializer.save()

            else:
                raise ValidationError(
                    "The data provided for updating an instrument are not valid"
                )

        except Instrument.DoesNotExist as exc:
            raise NotFound(f"No items where found with the given id {id}")

        self.instruments = Instrument.objects.all()
        return serializer.data

    def delete_instrument_by_id(self, id: uuid.UUID):
        try:

            instruments = get_object_or_404(self.instruments, pk=id)
            serializer = InstrumentsSerializer(instruments)
            instruments.delete()

        except Instrument.DoesNotExist as exc:
            raise NotFound(f"No items where found with the given id {id}")

        self.instruments = Instrument.objects.all()
        return serializer.data

    def get_instruments(self):
        serializer = InstrumentsSerializer(self.instruments, many=True)

        return serializer.data

    def add_instrument(self, instrument_data: Instrument):

        serializer = InstrumentsSerializer(data=instrument_data)

        if serializer.is_valid():
            serializer.save()
        else:
            raise ValidationError(
                "The data provided for registering a new instrument are not valid"
            )

        self.instruments = Instrument.objects.all()
        return serializer.data