我想設定一些引數并初始化 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
有人會在哪里初始化注入器以創建依賴項?
uj5u.com熱心網友回復:
也許你可以看看Django Applications
在您的應用程式檔案夾中,您可能有一個apps.py檔案:
from django.apps import AppConfig
class MyApp(AppConfig):
def ready(self):
# do stuff here
這是您的應用程式的入口點。
編輯:
有一個專案已經這樣做了:django-injector
uj5u.com熱心網友回復:
好的,我讓依賴注入作業,問題不是注入器,而是在class InstrumentsService:上面發布的我試圖做的事實:
def __init__(self, instruments: Instrument):
self.instruments = instruments.objects.all()
但是物件管理器不能通過 Django 物件訪問物件(類實體),而是直接通過類訪問。因此,如果我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
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/367915.html
標籤:Python 姜戈 Django 休息框架 依赖注入 django-views
