· 7 years ago · Jan 04, 2019, 01:28 PM
1import os
2import json
3
4from django.core.exceptions import ImproperlyConfigured
5
6
7# Set ENV.
8# ENV must be 'development' or 'production'
9ENV = 'development'
10
11# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
12BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
13CONFIG_DIR = os.path.dirname(os.path.abspath(__file__))
14CONFIG_VARIABLES_DIR = os.path.join(CONFIG_DIR, 'variables')
15
16# Set paths of variable files
17CONFIG_VARIABLES_FILE = os.path.join(CONFIG_VARIABLES_DIR, ENV + '.json')
18with open(CONFIG_VARIABLES_FILE) as file:
19 CONFIG_VARIABLES = json.loads(file.read())
20
21
22def get_config_variable(key, config_variable=CONFIG_VARIABLES, env=ENV):
23 try:
24 return config_variable[key]
25 except KeyError:
26 error_msg = "Set the variable '{}' in 'project/config/variables/{}.json'".format(key, env)
27 raise ImproperlyConfigured(error_msg)
28
29
30# Below variables will be loaded from development.py or production.py.
31# SECRET_KEY, DEBUG, ALLOWED_HOSTS
32
33
34SECRET_KEY = get_config_variable('SECRET_KEY')
35
36DEBUG = get_config_variable('DEBUG')
37
38ALLOWED_HOSTS = get_config_variable('ALLOWED_HOSTS')
39
40# ...