SoFunction
Updated on 2024-11-13

Django multi-environment configuration details

This article is also a small experience in the development project Tip, although very simple, but also a small help to many friends.

In our actual projects, we may encounter development environments, pre-launch environments, online environments and other environmental scenarios, so the application configuration may be different.

My experience has been to use environment variables to define the application runtime environment and make corresponding determinations in the code.

Specifically, I added some determination code in, roughly as follows:

APP_ENV = ('APP_ENV')
if APP_ENV == 'prod':
  from ._settings.prod_settings import *
elif APP_ENV == 'test':
  from ._settings.test_settings import *
else:
  from ._settings.dev_settings import *

First take the environment variable APP_ENV and according to APP_ENV do not pass to load the different configuration files in the _settings package.

For example, DEBUG is turned off in prod_settings.py:

# -*- coding: utf-8 -*-
 
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

And DEBUG is turned on in test_settings.py:

# -*- coding: utf-8 -*-
 
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

When starting the wsgi container, we can specify the APP_ENV environment variable.

For example, take advantage of being a developer:

ZDEVOPS_ENV=test python  runserver

Then again, when doing a production deployment with systemctl:

# Environment variables
Environment='APP_ENV=prod'
# Process working directories
WorkingDirectory=/www/python/myapp
# Execute commands
ExecStart=/usr/bin/gunicorn :application -w 4 -b 127.0.0.1:8000

This is the whole content of this article, I hope it will help you to learn more.