在Django视图中使用正确的设置常量

时间:2013-09-09 19:31:53

标签: python django django-views django-settings

我对Django很有经验,并且正在使用现在推荐的“多个设置文件”模式设置一个新项目。每个settings.py文件都将导入基本settings.py,然后覆盖特定设置。每个登台环境都有一个文件(dev,qa,prod)。启动Django进程时,我确保将settings标志设置为适当的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']

1 个答案:

答案 0 :(得分:4)

而不是

from myproj import settings

DO

from django.conf import settings

这就是DEBUG的工作原理:

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