Skip to content

Instantly share code, notes, and snippets.

@dkdndes
Created July 9, 2019 09:51
Show Gist options
  • Save dkdndes/bf2667102b581a2d47657795d9d7006e to your computer and use it in GitHub Desktop.
Save dkdndes/bf2667102b581a2d47657795d9d7006e to your computer and use it in GitHub Desktop.
Ensure unique django secret key at runtime
def ensure_secret_key_file():
"""Checks that secret.py exists in settings dir. If not, creates one
with a random generated SECRET_KEY setting."""
secret_path = os.path.join(BASE_DIR, 'secret.py')
if not os.path.exists(secret_path):
from django.utils.crypto import get_random_string
secret_key = get_random_string(
50, 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)')
with open(secret_path, 'w') as f:
f.write("SECRET_KEY = " + repr(secret_key) + "\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment