Refactor out the secret.txt file handling to a utils module

This commit is contained in:
x11x 2018-02-18 14:19:29 +10:00
parent 276a926fcb
commit 69655008e0
2 changed files with 15 additions and 10 deletions

View File

@ -11,7 +11,7 @@ https://docs.djangoproject.com/en/1.10/ref/settings/
""" """
import os import os
from django.core.management import utils from .utils import get_secret_from_file
# Build paths inside the project like this: os.path.join(BASE_DIR, ...) # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@ -21,15 +21,9 @@ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret! # SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY_FILE = os.path.join(BASE_DIR, "secret.txt") # See secret.py for how this is generated; uses a file 'secret.txt' in the root
# directory
try: SECRET_KEY = get_secret_from_file(os.path.join(BASE_DIR, "secret.txt"))
with open(SECRET_KEY_FILE, "r") as f:
SECRET_KEY = f.read().strip()
except EnvironmentError:
with open(SECRET_KEY_FILE, "w") as f:
SECRET_KEY = utils.get_random_secret_key()
f.write(SECRET_KEY)
# SECURITY WARNING: don't run with debug turned on in production! # SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False DEBUG = False

11
etesync_server/utils.py Normal file
View File

@ -0,0 +1,11 @@
from django.core.management import utils
def get_secret_from_file(path):
try:
with open(path, "r") as f:
return f.read().strip()
except EnvironmentError:
with open(path, "w") as f:
secret_key = utils.get_random_secret_key()
f.write(secret_key)
return secret_key