【问题标题】:Lightweight Django: settings.ALLOWED_HOSTS set as environment variable轻量级 Django:settings.ALLOWED_HOSTS 设置为环境变量
【发布时间】:2015-01-14 05:57:45
【问题描述】:

我正在关注来自 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

谁能告诉我怎么了?

【问题讨论】:

    标签: python django environment-variables


    【解决方案1】:

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

    【讨论】:

    • 但是我添加之后,我不能去同一个Hello World,而是得到一个Bad Request (400),你能告诉我为什么吗?谢谢!!
    • 这是因为 ALLOWED_HOSTS 和浏览器 url 中的主机名不匹配。将127.0.0.1 添加到ALLOWED_HOSTS 环境变量或将浏览器指向http://localhost:8000
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-03
    • 2013-01-29
    • 2015-02-06
    • 1970-01-01
    • 2014-12-17
    • 2018-07-13
    • 2016-01-11
    相关资源
    最近更新 更多