简体   繁体   English

如何将环境变量添加到django项目中

[英]How do you add environment variables to your django project

I'm trying to set up my project so that it can use environment variables locally 我正在尝试设置我的项目,以便它可以在本地使用环境变量

Ive tried adding it to the end of my activate file and a list of other things. 我已经尝试将它添加到我的激活文件的末尾和其他东西的列表。 I'm trying to use this 我正在尝试使用它

from .base import *

    if os.environ['DJANGO_SERVER_TYPE'] == 'local':
        try:
            from .local import *
        except:
            pass

    if os.environ['DJANGO_SERVER_TYPE'] == 'production':
        try:
            from .production import *
        except:
            pass

I am a real novice and often things are explained brief and matter of factly. 我是一个真正的新手,事实上经常解释简短和事实。 So a thorough explanation would really be beneficial to me in how to implement this thanks. 因此,如何实现这一点,彻底的解释将对我有益。 I've NEVER done anything n Bash. 我从来没有做过任何事情。 Ive tried doing this 我试过这样做

export KEY=VALUE

in the activate file, only for it not to be recognized by the system, and I had to remove it in order to use my local server 在激活文件中,只是因为它不被系统识别,我必须将其删除才能使用我的本地服务器

If you're running it through the Django web server, you can pass environment variables the same way you would to any other command: 如果您通过Django Web服务器运行它,您可以像对任何其他命令一样传递环境变量:

DJANGO_SERVER_TYPE="local" ./manage.py runserver

If you're running it through a web server like Apache, you can set environment variables through your virtual host configuration: 如果您通过Apache等Web服务器运行它,则可以通过虚拟主机配置设置环境变量:

SetEnv DJANGO_SERVER_TYPE local

Install the environ library and add the following code to your settings file: 安装environ库并将以下代码添加到您的设置文件中:

root_path = environ.Path(__file__) - 2
env = environ.Env(DEBUG=(bool, False), DJANGO_ENV=(str, 'dev')) # set default    values and casting
environ.Env.read_env(root_path('.env')) 

Add a file called .env on the root of your project folder with variables formatted like: 在项目文件夹的根目录中添加一个名为.env的文件,其变量格式如下:

DEBUG=on    

I have a settings module that contains something like the following: 我有一个设置模块,其中包含以下内容:

…
import os
from django.core.exceptions import ImproperlyConfigured
…

def _require_env(name):
    """Raise an error if the environment variable isn't defined"""
    value = os.getenv(name)
    if value is None:
        raise ImproperlyConfigured('Required environment variable "{}" is not set.'.format(name))
    return value

…

SECRET_KEY = _require_env('SOMETHING_SECRET_KEY')

_db_host = os.getenv('SOMETHING_MYSQL_HOST', 'mysql')
_db_port = os.getenv('SOMETHING_MYSQL_PORT', 3306)   
_db_name = _require_env('SOMETHING_MYSQL_DATABASE')         
_db_user = _require_env('SOMETHING_MYSQL_USER')             
_db_password = _require_env('SOMETHING_MYSQL_PASSWORD')

DATABASES = {'default': {'ENGINE': 'django.db.backends.mysql',
                     'NAME': _db_name,                    
                     'HOST': _db_host,                    
                     'PORT': _db_port,                    
                     'USER': _db_user,                    
                     'PASSWORD': _db_password,
    … } }

and so on. 等等。

_require_env is for environment variables that must be set. _require_env用于必须设置的环境变量。 If those environment values are not found, Django immediately raises an ImproperlyConfigured error. 如果找不到这些环境值,Django会立即引发一个ImproperlyConfigured错误。 In other cases I just use os.getenv with a default value. 在其他情况下,我只使用带有默认值的os.getenv

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM