【问题标题】:How can I resolve this python and django settings import idiosyncrasy?如何解决这个 python 和 django 设置导入特性?
【发布时间】:2023-04-07 15:14:01
【问题描述】:

我有这样的文件布局:
settings/
----__init__.py
----common.py
----configs/
--------constants1.py
--------constants2.py
----debug/
--------include1&2.py
--------include1.py
--------include2.py

当我导入settings.debug.include1 时,我希望设置文件执行/导入common.py 然后用适当的常量文件覆盖common.py 中的设置。问题是,这没有发生。有没有办法以这种方式实现我的目标?

【问题讨论】:

  • “指定settings.debug.include_.py”是指import settings.debug.include1吗?
  • 哦,在使用设置的代码中,您想说from settings import * 并始终检索正确的设置集?
  • 好吧,您可以将决定加载哪组设置的逻辑放入 common.py 并从那里导入适当的调试/配置模块。

标签: python django import settings


【解决方案1】:

没有。在settings/__init__.py 中使用from ... import *execfile() 加载相应的文件。

【讨论】:

    【解决方案2】:

    由于大多数 cmets 已经暗示您可以在适当的文件中使用from module import *。它们可能如下所示..

    --

    # settings/common.py
    
    DEBUG = False
    

    --

    # settings/configs/constants1.py
    
    CONSTANT_1 = 'One'
    

    --

    # settings/configs/constants2.py
    
    CONSTANT_2 = 'Two'
    

    --

    # settings/debug/include1.py
    
    from settings.common import *
    from settings.configs.constants1 import *
    
    # Override settings here
    DEBUG = True
    CONSTANT_1 = '1'
    

    --

    # settings/debug/include2.py
    
    from settings.common import *
    from settings.configs.constants2 import *
    
    # Override settings here
    DEBUG = True
    CONSTANT_2 = '2'
    

    并且对于2个debug的组合包括

    # settings/debug/include1and2.py
    
    from settings.debug.include1 import *
    from settings.debug.include2 import *
    

    # settings/debug/include1and2.py
    
    from settings.common import *
    from settings.configs.constants1 import *
    from settings.configs.constants2 import *
    
    # Override settings here
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-10
      • 1970-01-01
      • 2016-11-20
      • 1970-01-01
      • 1970-01-01
      • 2019-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多