· 7 years ago · Apr 28, 2018, 02:06 AM
1"""
2Two things are wrong with Django's default `SECRET_KEY` system:
3
41. It is not random but pseudo-random
52. It saves and displays the SECRET_KEY in `settings.py`
6
7This snippet
81. uses `SystemRandom()` instead to generate a random key
92. saves a local `secret.txt`
10
11The result is a random and safely hidden `SECRET_KEY`.
12"""
13
14import os, random, string
15try:
16 SECRET_KEY
17except NameError:
18 PROJECT_PATH = ''
19 SECRET_FILE = os.path.join(PROJECT_PATH, 'secret.txt')
20 try:
21 SECRET_KEY = open(SECRET_FILE).read().strip()
22 except IOError:
23 try:
24 SECRET_KEY = ''.join([random.SystemRandom().choice("{}{}{}".format(string.ascii_letters, string.digits, string.punctuation)) for i in range(50)])
25 secret = open(SECRET_FILE, 'w')
26 secret.write(SECRET_KEY)
27 secret.close()
28 except IOError:
29 Exception('Please create a %s file with random characters \
30 to generate your secret key!' % SECRET_FILE)