Skip to content

Instantly share code, notes, and snippets.

@kelvan
Created January 2, 2017 16:02
Show Gist options
  • Save kelvan/202479e0335e1a62a3c4143b60260848 to your computer and use it in GitHub Desktop.
Save kelvan/202479e0335e1a62a3c4143b60260848 to your computer and use it in GitHub Desktop.
Some (maybe hackish) approach to generate SECRET_KEY on first run
# Put this code in your settings file
# Saves new secret key to secret.key file in same folder as your settings
import logging
logger = logging.getLogger(__name__)
## Secret key generation functions
secret_key_fn = os.path.join(os.path.dirname(__file__), 'secret.key')
def create_secret_key():
import random
import string
return ''.join(
[random.SystemRandom().choice(string.printable) for i in range(50)]
)
def create_secret_key_file(secret_key):
with open(secret_key_fn, 'w') as f:
f.write(secret_key)
return secret_key
def load_secret_key_file():
with open(secret_key_fn, 'r') as f:
# Read one byte more to check content length
skey = f.read(51)
if len(skey) != 50:
# We probably could just replace file with a new generated key,
# but it's safer to let the user handle it
raise ValueError('Content of secret_key file is wrong')
return skey
if os.path.exists(secret_key_fn):
logger.info('Load secret key from file')
SECRET_KEY = load_secret_key_file()
else:
logger.warning('Unable to import SECRET_KEY generating a new one')
SECRET_KEY = create_secret_key_file(create_secret_key())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment