声明要与 mod_wsgi/apache 一起使用的 Django 设置

Declare Django settings to use with mod_wsgi/apache

我的 Django 项目中有多个设置文件(base.py、local.py、production.py)。

在本地,我通过

启动 Django 开发服务器
python manage.py runserver --settings=config.settings.local

如何告诉 mod_wsgi 使用同一个文件?我正在我的本地 apache 实例上对此进行测试,但需要为我的生产 apache 实例弄清楚同样的事情。

--settings=config.settings.production

当前 httpd-vhosts.conf:

WSGIDaemonProcess secureDash python-path=/Users/user/projects/secureDash_project/secureDash python-home=/Users/user/.venvs/securedash_py3.6
WSGIProcessGroup secureDash
WSGIScriptAlias / /Users/user/projects/secureDash_project/config/wsgi.py

我在 apache 日志中看到的错误:

ModuleNotFoundError: No module named 'secureDash.settings'

Django 1.11

mod_wsgi-4.5.15

阿帕奇 2.4.18

您可以通过设置 DJANGO_SETTINGS_MODULE 环境变量来做到这一点。您可以在 Apache 虚拟主机配置中执行此操作,也可以在 wsgi 文件本身中执行此操作。

我通过在每个环境中将 DJANGO_SETTINGS_MODULE 添加到我的 secrets.json 文件来解决这个问题。

secrets.json:

{
  "FILENAME": "secrets.json",
  "SECRET_KEY": "someSuperSecretiveSecret!",
  "DJANGO_SETTINGS_MODULE": "config.settings.local"
}

wsgi.py:

import json
from django.core.exceptions import ImproperlyConfigured
from pathlib import Path
...

# Directory Paths
BASE_DIR = Path(__file__).resolve().parent

# JSON-based secrets module
SECRETS_JSON = str(BASE_DIR) + '/secrets.json'

with open(SECRETS_JSON) as f:
    secrets = json.loads(f.read())


def get_secret(setting, secrets=secrets):
    '''Get the secret variable or return explicit exception'''
    try:
        return secrets[setting]
    except KeyError:
        error_msg = 'Set the {0} environment variable'.format(setting)
        raise ImproperlyConfigured(error_msg)


DJANGO_SETTINGS_MODULE = get_secret('DJANGO_SETTINGS_MODULE')

os.environ.setdefault("DJANGO_SETTINGS_MODULE", DJANGO_SETTINGS_MODULE)