Django settings.py:单独的本地和全局配置

发布于 2024-10-31 04:12:48 字数 156 浏览 3 评论 0原文

我想知道是否可以将 Django 中的“本地”配置(静态的本地路径、必须是绝对的模板内容、本地数据库信息等...)与“全局”配置(URL、中间件类)分开、安装的应用程序等...),这样几个人就可以通过 Git 或 SVN 处理同一个项目,而不必在每次完成提交时重写本地设置!

谢谢!

I was wondering if it was possible to separate the "local" configuration in Django (Local path to static, templates content which have to be absolute, local DB info, etc...) from the "global" configuration (URL, Middleware classes, installed apps, etc...) so that several people can work on a same project over Git or SVN without having to rewrite the local settings every time there is a commit done!

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

傲影 2024-11-07 04:12:48

是的,绝对是。 settings.py 文件只是 Python,因此您可以在其中执行任何操作 - 包括动态设置以及导入其他文件以覆盖。

所以这里有两种方法。第一个是不要硬编码任何路径,而是动态计算它们。

PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
TEMPLATE_DIRS = [
    os.path.join(PROJECT_ROOT, "templates"),
]

神奇的Python关键字__file__给出了当前文件的路径。

第二种是在 SVN 之外有一个 local_settings.py 文件,该文件在主 settings.py 的末尾导入并覆盖其中的任何设置:

try:
    from local_settings import *
except ImportError:
    pass

try/ except是为了确保即使 local_settings 不存在它仍然可以工作。

当然,您可以尝试结合使用这些方法。

Yes, definitely. The settings.py file is just Python, so you can do anything in there - including setting things dynamically, and importing other files to override.

So there's two approaches here. The first is not to hard-code any paths, but calculate them dynamically.

PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
TEMPLATE_DIRS = [
    os.path.join(PROJECT_ROOT, "templates"),
]

etc. The magic Python keyword __file__ gives the path to the current file.

The second is to have a local_settings.py file outside of SVN, which is imported at the end of the main settings.py and overrides any settings there:

try:
    from local_settings import *
except ImportError:
    pass

The try/except is to ensure that it still works even if local_settings is not present.

Naturally, you could try a combination of those approaches.

未央 2024-11-07 04:12:48

您可以将配置分成不同的文件。由于它们是用 python 编写的,您只需使用 import local_settings 从其他设置文件导入设置,您甚至可以将导入放入条件中,以根据某些上下文导入本地设置。

查看文档: http://docs.djangoproject.com/en/dev /主题/设置/

You can split up your configuration into different files. As they are written in python you'd just import the settings from the other settings file using import local_settings you even can put the import in a conditional to import local settings depending on some context.

Take a look at the documentation: http://docs.djangoproject.com/en/dev/topics/settings/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文