Skip to content

Instantly share code, notes, and snippets.

@ndarville
Created August 24, 2012 17:01
Show Gist options
  • Save ndarville/3452907 to your computer and use it in GitHub Desktop.
Save ndarville/3452907 to your computer and use it in GitHub Desktop.
Generating a properly secure SECRET_KEY in Django
"""
Two things are wrong with Django's default `SECRET_KEY` system:
1. It is not random but pseudo-random
2. It saves and displays the SECRET_KEY in `settings.py`
This snippet
1. uses `SystemRandom()` instead to generate a random key
2. saves a local `secret.txt`
The result is a random and safely hidden `SECRET_KEY`.
"""
try:
SECRET_KEY
except NameError:
SECRET_FILE = os.path.join(PROJECT_PATH, 'secret.txt')
try:
SECRET_KEY = open(SECRET_FILE).read().strip()
except IOError:
try:
import random
SECRET_KEY = ''.join([random.SystemRandom().choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)])
secret = file(SECRET_FILE, 'w')
secret.write(SECRET_KEY)
secret.close()
except IOError:
Exception('Please create a %s file with random characters \
to generate your secret key!' % SECRET_FILE)
@almereyda
Copy link

Another form of the one line command is:

$ python -c "from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())"

from https://stackoverflow.com/a/68085559/1959568.

Please note that your local interpreter might only be available through a versioned binary name, like python3, and/or its absolute path, e.g. /usr/lib/python3.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment