轻量级Django:settings.ALLOWED_HOSTS设置为环境变量

时间:2015-01-14 05:57:46

标签: python django environment-variables

我跟随来自O' Reilly的Julia Elman和Mark Lavin的Lightweight Django。在第1章中,我不能将ALLOWED_HOSTS设置为环境变量。

当我运行python hello.py runserver时,我会继续CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False

这是我的hello.py

import os
import sys
from django.conf import settings

DEBUG = os.environ.get('DEBUG', 'on') == 'on'
SECRET_KEY = os.environ.get('SECRET_KEY', os.urandom(32))
ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', 'localhost').split(',')

settings.configure(
    DEBUG=DEBUG,
    SECRET_KEY=SECRET_KEY,
    ROOT_URLCONF=__name__,
    MIDDLEWARE_CLASSES=(
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ),
)

from django.conf.urls import url
from django.core.wsgi import get_wsgi_application
from django.http import HttpResponse

def index(request):
    return HttpResponse('Hello World')

urlpatterns = (
    url(r'^$', index),
)

application = get_wsgi_application()

if __name__ == "__main__":
    from django.core.management import execute_from_command_line
    execute_from_command_line(sys.argv)

我已完成export DEBUG=offexport ALLOWED_HOSTS=localhost,example.com 我确信我有环境变量:

$printenv DEBUG
off
$printenv ALLOWED_HOSTS
localhost,example.com

有人可以告诉我出了什么问题吗?

1 个答案:

答案 0 :(得分:4)

您忘记在ALLOWED_HOSTS来电中添加settings.configure()参数。

相关问题