上QQ阅读APP看书,第一时间看更新
How to do it...
To use local settings in your project, first we must draw values from environment variables for any configurations in settings.py that will differ across environments or that would be a security risk if stored in version control. It is a good practice to be very clear and unique when naming these variables, but also take into account those that already exist in the environment. Some examples follow:
- Whether or not to use DEBUG mode will generally differ per environment, where debugging would be on in development, but not by default:
# settings.py
DEBUG = False
if os.environ.get('DJANGO_USE_DEBUG'):
DEBUG = True
- Similarly, we might want the debug_toolbar to be active in development, or perhaps only in certain situations even then, so we could add it only when necessary:
# settings.py
INSTALLED_APPS = [
# ...
]
if os.environ.get('DJANGO_USE_DEBUG_TOOLBAR'):
INSTALLED_APPS += ('debug_toolbar',)
MIDDLEWARE = [
# ...
]
if os.environ.get('DJANGO_USE_DEBUG_TOOLBAR'):
MIDDLEWARE += (
'debug_toolbar.middleware.DebugToolbarMiddleware',)
- Perhaps we use a SQLite3 database in testing, but a MySQL database in development, staging, and production. Also, in development, the MySQL database might be on localhost, but have its own separate domain in staging and production. Finally, storing the credentials for the connection in any environment is a security risk. We can handle all of these scenarios just as easily with the following updates to settings.py:
# settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
if os.environ.get('MYSQL_HOST'):
DATABASES['default'] = {
'ENGINE': 'django.db.backends.mysql',
'HOST': os.environ.get('MYSQL_HOST'),
'NAME': os.environ.get('MYSQL_DATABASE'),
'USER': os.environ.get('MYSQL_USER'),
'PASSWORD': os.environ.get('MYSQL_PASSWORD'),
}