You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 into os.environ.
  • Django loads your settings file the moment get_wsgi_application() runs. That means when your settings try to read VAR_1 or VAR_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 the application function, right after we inject the environment variables. This ensures Django loads settings only after the variables are available in os.environ.
  • We kept the DJANGO_SETTINGS_MODULE assignment at the bottom (you could also put it inside the application function if needed—just make sure it's before get_wsgi_application()).
  • We added a check to only copy variables that actually exist in the WSGI environ dictionary, avoiding overwriting existing variables with None if 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:08:45