简体   繁体   English

如何从第三方模块访问Django设置?

[英]how to access django settings from 3rd party module?

i'm writing a django-agnostic module, that will be importet anywhere inside django subdir tree. 我正在编写一个与django无关的模块,它将在django子目录树内的任何地方都是重要的。

I want that if this module is imported from within any arbitrary django project, it will detect that it's running in a django environment, and it will find and import settings.py, from anywhere inside the project? 我希望,如果此模块是从任意django项目中导入的,它将检测到它在django环境中运行,并且可以从项目内部的任何位置找到并导入settings.py?

eg \\django \\app \\import XXX.settings ? 例如\\ django \\ app \\ import XXX.settings?

\\django \\project \\somewhere \\import XXX.settings \\ django \\ project \\ somewhere \\ import XXX.settings

(I'm, looking for a general purpose solution, not in particular to a specific dir.) (我正在寻找通用解决方案,而不是特别针对特定目录。)

Your module should access django settings in the standard way: 您的模块应以标准方式访问django设置:

from django.conf import settings

from https://docs.djangoproject.com/en/1.8/topics/settings/#using-settings-in-python-code 来自https://docs.djangoproject.com/en/1.8/topics/settings/#using-settings-in-python-code

Also note that your code should not import from either global_settings or your own settings file. 另请注意,您的代码不应从global_settings或您自己的设置文件中导入。 django.conf.settings abstracts the concepts of default settings and site-specific settings; django.conf.settings抽象了默认设置和特定于站点的设置的概念; it presents a single interface. 它提供了一个单一的界面。 It also decouples the code that uses settings from the location of your settings. 它还将使用设置的代码与设置的位置解耦。

If your module has it's own settings, they can be configured in the project's settings.py. 如果您的模块具有自己的设置,则可以在项目的settings.py中对其进行配置。 You can hard-code sensible defaults in your module, and you can raise ImproperlyConfigured if you require a settings.py value. 您可以在模块中对合理的默认值进行硬编码,如果需要settings.py值,则可以提高ImproperlyConfigured

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

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