Skip to content

Instantly share code, notes, and snippets.

@neino3
Last active August 29, 2015 14:21
Show Gist options
  • Save neino3/788e157e8f5e5d5174ef to your computer and use it in GitHub Desktop.
Save neino3/788e157e8f5e5d5174ef to your computer and use it in GitHub Desktop.
def generate_or_read_from_file(key_file='.secret_key', key_length=64):
"""Multiprocess-safe secret key file generator.
Useful to replace the default (and thus unsafe) SECRET_KEY in settings.py
upon first start. Save to use, i.e. when multiple Python interpreters
serve the dashboard Django application (e.g. in a mod_wsgi + daemonized
environment). Also checks if file permissions are set correctly and
throws an exception if not.
"""
lock = lockfile.FileLock(key_file)
with lock:
if not os.path.exists(key_file):
key = generate_key(key_length)
with open(key_file, 'w') as f:
f.write(key)
os.chmod(key_file, 0600)
else:
if oct(os.stat(key_file).st_mode & 0o777) != '0600':
raise FilePermissionError("Insecure key file permissions!")
with open(key_file, 'r') as f:
key = f.readline()
return key
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment