【问题标题】:Using the correct settings constant in Django view在 Django 视图中使用正确的设置常量
【发布时间】:2013-09-13 09:00:00
【问题描述】:

我对 Django 有一定的经验,并且正在使用现在推荐的“多个设置文件”模式设置一个新项目。每个 settings.py 文件都会导入一个基本的 settings.py,然后覆盖特定的设置。每个暂存环境(dev、qa、prod)将有一个文件。启动 Django 进程时,我确保将设置标志设置为适当的 settings.py 文件,如下所示

manage.py runserver --settings=myproj.settings.dev

manage.py runfcgi --settings=myproj.settings.prod method=threaded daem...[more flags]

我的问题是,如何将特定于环境的常量放入视图的函数中。我的项目有一些特定的常量(curl cert/host/port),每个环境都不同。目前我只知道如何在导入路径中包含环境,但这对我不起作用,如果有人可以请帮助,那就太棒了。

这是一个示例 views.py 文件,它应该有助于让我的问题更清楚一些。

# A sample Django view.py file

from django.template.response import TemplateResponse
from myproj import settings

def index(request):
    # these assignments work, but I have to add conditional logic to pick the correct
    # value, I would prefer not to do this.
    dev_curl_host = settings.dev.CONNECT['host']
    qa_curl_host = settings.qa.CONNECT['host']
    prod_curl_host = settings.prod.CONNECT['host']

    # I want to do something like this, where the settings import get assigned the 
    # correct values for the staging environment.
    # It seems like Django is already doing this with settings like Debug, how?
    curl_host = settings.CONNECT['host']

【问题讨论】:

    标签: python django django-views django-settings


    【解决方案1】:

    代替

    from myproj import settings
    

    from django.conf import settings
    

    这就是 DEBUG 起作用的原因:

    https://docs.djangoproject.com/en/dev/topics/settings/#using-settings-in-python-code

    【讨论】:

    • 选择这个答案,虽然下面的答案也是正确的,因为它是先提交的,并且指向 django 文档的链接也很有帮助。谢谢!
    • @macguru2000 当然,顺便说一句,您绝对应该阅读Two Scoops of Django 书中的“设置和要求文件”一章——它正是这个线程的主题。
    • 我现在实际上正在阅读那本书,到目前为止我对它非常满意,但我一定错过了它提到从 django.conf 获取设置的区域。现在我知道了,这完全有道理。谢谢!
    猜你喜欢
    • 2014-08-28
    • 2016-07-30
    • 2022-10-30
    • 1970-01-01
    • 1970-01-01
    • 2012-08-01
    • 2017-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多