1

I use customer settings in my django project as in my manage.py. I write:

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "setting.windows")
...

I want to run my program in different settings when I run my code like:

python manage.py runserver --settings=twoscoops.settings.local

In my settings.py I also add some my private program variable, different settings.py use different variables. If my models.py or other classes file want to import those variable defined in my setting file. How do I write the import Statement?</p>

I mean if I do

import twoscops.settings.local

I may change the environment variable, when I use other settings. HOW to do it?

4

2 回答 2

1

一个很好的方法实际上是在你的操作系统中设置一个环境变量,然后在你的 Python 代码中从一个environment模块中检查它(如下所示)。

注意:就目录结构而言,使用适合您的任何东西 - 我<my app>/conf/envs/<some env>.py用于特定于环境的设置

# twoscoops/conf/envs/current.py
"""
Imports the proper settings, based on the deployment environment's name (set
as an environment variable), defaulting to local settings.
"""
import os

from django.core.exceptions import ImproperlyConfigured


# Environments (these can be called anything you want)
ENV_LOCAL = 'local'
ENV_PROD = 'prod'
DEPLOYMENT_ENVS = (ENV_LOCAL, ENV_PROD)

# Get the deployment environment's name from the os environment
DEPLOYMENT_ENV = os.getenv('DJANGO_DEPLOYMENT_ENV', ENV_LOCAL)

# Ensure the deployment env's name is valid
if DEPLOYMENT_ENV not in DEPLOYMENT_ENVS:
    raise ImproperlyConfigured(
        u'Invalid `DJANGO_DEPLOYMENT_ENV`: {d}'.format(d=DEPLOYMENT_ENV)
    )

# Import env-specific settings

if DEPLOYMENT_ENV == ENV_LOCAL:
    # Local, native testing
    from twoscoops.conf.envs.local import *

if DEPLOYMENT_ENV == ENV_PROD:
    # Production
    from twoscoops.conf.envs.prod import *

只需添加from twosscoops.conf.envs.current import *到您的每个主要设置模块(您可能只有一个,或者您可能有一个用于 API、一个用于网站等)。

您会注意到上面的示例默认为twoscoops.conf.envs.local. 当您想使用另一个环境(在我的示例中,只有prod本地环境)时,只需DJANGO_DEPLOYMENT_ENV在启动 shell 或服务器之前添加环境变量(或在启动 uWSGI 之前在 Upstart 脚本中等),如下所示:

you@your-server$ export DJANGO_DEPLOYMENT_ENV=prod
you@your-server$ python manage.py shell

在 Windows 中,您也可以设置环境变量(我相信命令行和 GUI - Google 会知道更多)。

于 2013-06-17T04:32:06.560 回答
0

你也可以为你的本地开发作弊,然后简单地放在你的虚拟环境脚本export DJANGO_VARIABLE=value-of-variable的末尾。activate

请注意,对于生产,您需要在您的 Apache vhost 配置中添加类似的内容(我确信这与 nginx 类似):

SetEnv DJANGO_VARIABLE value-of-variable

请注意 vhost 配置中的变量名称和值之间缺少等号。

于 2013-06-17T13:47:00.773 回答