Skip to content

Instantly share code, notes, and snippets.

@squamous
Last active July 25, 2016 07:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save squamous/ee363a1d761645d4c78800ff3aa19129 to your computer and use it in GitHub Desktop.
Save squamous/ee363a1d761645d4c78800ff3aa19129 to your computer and use it in GitHub Desktop.
generate secure Django SECRE_KEY
"""
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`.
"""
import os
try:
SECRET_KEY
except NameError:
SECRET_FILE = os.path.join('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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment