Skip to content

Instantly share code, notes, and snippets.

@aquaerius
Forked from ndarville/secret-key-gen.py
Created April 20, 2018 10:17
Show Gist options
  • Save aquaerius/8a78fea55344c6fc78997eb218cb34e3 to your computer and use it in GitHub Desktop.
Save aquaerius/8a78fea55344c6fc78997eb218cb34e3 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`.
"""
import os, random, string
try:
SECRET_KEY
except NameError:
PROJECT_PATH = ''
SECRET_FILE = os.path.join(PROJECT_PATH, 'secret.txt')
try:
SECRET_KEY = open(SECRET_FILE).read().strip()
except IOError:
try:
SECRET_KEY = ''.join([random.SystemRandom().choice("{}{}{}".format(string.ascii_letters, string.digits, string.punctuation)) for i in range(50)])
secret = open(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)
Ag&ys<A|QN\$h{m{[{^MO2<a6602]h1`aVu}vSsSo3EFqcv9uG
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment