轻量级 Django:settings.ALLOWED_HOSTS 设置为环境变量
Lightweight Django: settings.ALLOWED_HOSTS set as environment variable
我正在关注来自 O'Reilly 的 Julia Elman 和 Mark Lavin 的轻量级 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=off
和 export ALLOWED_HOSTS=localhost,example.com
我确定我有环境变量:
$printenv DEBUG
off
$printenv ALLOWED_HOSTS
localhost,example.com
谁能告诉我怎么了?
您忘记在 settings.configure()
调用中添加 ALLOWED_HOSTS
参数。
我正在关注来自 O'Reilly 的 Julia Elman 和 Mark Lavin 的轻量级 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=off
和 export ALLOWED_HOSTS=localhost,example.com
我确定我有环境变量:
$printenv DEBUG
off
$printenv ALLOWED_HOSTS
localhost,example.com
谁能告诉我怎么了?
您忘记在 settings.configure()
调用中添加 ALLOWED_HOSTS
参数。