Django 1.11:WSGI设置环境变量后Settings文件无法获取问题
Fixing Django 1.11 WSGI Environment Variable Passing to Settings
Hey there, let's break down why your environment variables aren't showing up in your Django settings file, and how to fix it.
The Root Cause
Looking at your current wsgi.py code, the key issue is the order of operations:
- You're calling
get_wsgi_application()before you handle passing the WSGI environment variables intoos.environ. - Django loads your settings file the moment
get_wsgi_application()runs. That means when your settings try to readVAR_1orVAR_2, those variables haven't been added to the environment yet—so they're nowhere to be found.
The Fixed wsgi.py Code
Here's the adjusted version that ensures your environment variables are available when Django loads its settings:
# -*- coding: utf-8 -*- import os import sys from django.core.wsgi import get_wsgi_application PATH = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)))) if PATH not in sys.path: sys.path.append(PATH) # Define which WSGI environment variables to pass through ENV_VARIABLES_TO_PASS = ['VAR_1', 'VAR_2'] def application(environ, start_response): # Inject WSGI environment variables into os.environ FIRST for var_name in ENV_VARIABLES_TO_PASS: if var_name in environ: os.environ[var_name] = environ[var_name] # Now load the Django WSGI application (this triggers settings loading) django_application = get_wsgi_application() return django_application(environ, start_response) # Set your settings module before anything else os.environ['DJANGO_SETTINGS_MODULE'] = 'cms.settings.qa'
Key Changes Explained
- We moved the
get_wsgi_application()call inside theapplicationfunction, right after we inject the environment variables. This ensures Django loads settings only after the variables are available inos.environ. - We kept the
DJANGO_SETTINGS_MODULEassignment at the bottom (you could also put it inside theapplicationfunction if needed—just make sure it's beforeget_wsgi_application()). - We added a check to only copy variables that actually exist in the WSGI
environdictionary, avoiding overwriting existing variables withNoneif they're missing.
Testing It Out
Once you update your wsgi.py, you can verify the variables are accessible in your settings file by adding something like this temporarily:
# In cms/settings/qa.py import os print("VAR_1 value:", os.environ.get('VAR_1')) print("VAR_2 value:", os.environ.get('VAR_2'))
Just remember to remove those print statements once you confirm it's working!
内容的提问来源于stack exchange,提问作者Yossi Shaish
相关产品推荐
相关产品推荐

