Django - 如何在应用程序内共享配置常量?
有时,在 django 应用程序中的各个代码文件之间共享某些常量是有益的。
示例:
- 各种模块\命令等中使用的转储文件的名称或位置
- 整个应用程序的调试模式打开\关闭
- 站点特定配置
执行此操作的优雅\Pythonic 方式是什么?
It is sometimes beneficial to share certain constants between various code files in a django application.
Examples:
- Name or location of dump file used in various modules\commands etc
- Debug mode on\off for the entire app
- Site specific configuration
What would be the elegant\pythonic way of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
已经有一个项目范围的
settings.py
文件。这是放置您自己的自定义设置的完美位置。There's already a project-wide
settings.py
file. This is the perfect place to put your own custom setttings.您可以在 settings.py 中提供设置,就像
在任何模块中您可以像这样获取它
you can provide settings in your settings.py like
and in any module you can fetch it like
创建配置模块。
Configuration.py:(在您的项目/应用程序源目录中)
从其他源文件导入它:
Create a configuration module.
Configuration.py: (in your project/app source directory)
Import it from other source files:
Django 应用程序应该(或多或少)可插入。因此,您不应该侵入应用程序的代码来参数化您想要的内容(如果您必须这样做,那将是一团糟!想象一下您想要升级您在互联网上下载的应用程序......您必须重新破解新版本的代码?!?)。
因此,您不应在应用级别添加应用级别设置,而应将它们放在项目范围
settings.py
中的某个位置。Django apps are meant to be (more or less) pluggable. Therefore, you are not supposed to hack into the code of an app in order to parametrize what you want (it would be quite a mess if you had to do this ! Imagine you want to upgrade an app you downloaded on internet... you would have to re-hack into the code of the new version ?!?).
For this reason you shouldn't add app-level settings at the app level, but rather put them together somewhere in your project-wide
settings.py
.