You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django应用类似main.py的入口是什么?Injector该在哪里初始化?

初始化Injector的最佳位置

Django应用启动阶段唯一的用户自定义执行入口是对应App的AppConfig.ready()方法,该方法会在Django加载完全部模型、配置后仅执行一次,完全符合Injector初始化、单例依赖绑定的需求。

具体实现步骤

  1. 在应用的apps.py中完成Injector初始化和依赖绑定
    修改你的Instruments/apps.py文件,代码如下:
import os
from django.apps import AppConfig
from injector import Injector, Module, singleton
from .models import Instrument
from .services import InstrumentsService

# 全局Injector实例,其他模块直接导入使用
injector = None

class DependencyModule(Module):
    def configure(self, binder):
        # 按需绑定所有依赖的作用域和实现类
        binder.bind(Instrument, to=Instrument, scope=singleton)
        binder.bind(InstrumentsService, to=InstrumentsService, scope=singleton)

class InstrumentsConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'Instruments'

    def ready(self):
        global injector
        # 开发模式下避免重载进程重复初始化
        if os.environ.get('RUN_MAIN') != 'true':
            return
        # 全局仅初始化一次Injector
        injector = Injector(DependencyModule())
  1. 修改ViewSet的实例化逻辑,触发依赖注入
    Django默认的ViewSet实例化逻辑不会走Injector,需要重写as_view方法,从已初始化的Injector中获取ViewSet实例:
from Instruments.apps import injector

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

    @classmethod
    def as_view(cls, actions=None, **initkwargs):
        # 从Injector获取已完成依赖注入的实例
        view_instance = injector.get(cls)
        return super().as_view(actions=actions, **initkwargs, instance=view_instance)
    
    # 剩下的原有方法保持不变即可

额外优化建议

你当前InstrumentsService中把Instrument.objects.all()存在实例属性的写法会导致缓存脏数据,虽然你在增删改操作后手动刷新了查询集,但如果有其他服务修改了Instrument表数据,还是会出现数据不一致,建议直接在需要查询的时候再调用Instrument.objects方法,不要提前存查询集。


内容的提问来源于stack exchange,提问作者KZiovas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 18:36:08