Django 3 Web Development Cookbook
上QQ阅读APP看书,第一时间看更新

There's more...

Instead of environment variables, you can also use text files with sensitive information that won't be tracked under version control. They can be YAML, INI, CSV, or JSON files, placed somewhere on the hard disk. For example, for a JSON file, you would have the get_secret() function, like this:

# settings/_base.py
import os
import json


with open(os.path.join(os.path.dirname(__file__), 'secrets.json'), 'r')
as f:
secrets = json.loads(f.read())


def get_secret(setting):
"""Get the secret variable or return explicit exception."""
try:
return secrets[setting]
except KeyError:
error_msg = f'Set the {setting} secret variable'
raise ImproperlyConfigured(error_msg)

This reads a secrets.json file from the settings directory and expects it to have at least the following structure:

{
"DATABASE_NAME": "myproject",
"DATABASE_USER": "myproject",
"DATABASE_PASSWORD": "change-this-to-database-password",
"DJANGO_SECRET_KEY": "change-this-to-50-characters-long-random-string"
}

Make sure that the secrets.json file is ignored from the version control, but for convenience, you can create sample_secrets.json with empty values and put it under version control:

{
"DATABASE_NAME": "",
"DATABASE_USER": "",
"DATABASE_PASSWORD": "",
"DJANGO_SECRET_KEY": "change-this-to-50-characters-long-random-string"
}