繁体   English   中英

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

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

我想设置一些参数并初始化 Injector object,因为我想在我的 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()

但是 object 管理器无法访问 Django object thourgh 对象(类实例),而是直接通过 ZA2F2221ED4F8EBC2CBB4 所以如果我更正class InstrumentsService:到这个并使用这个django-injector模块Django 注射器一切正常:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM