· 9 years ago · Nov 26, 2016, 11:22 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"""
13try:
14 SECRET_KEY
15except NameError:
16 SECRET_FILE = os.path.join(PROJECT_PATH, 'secret.txt')
17 try:
18 SECRET_KEY = open(SECRET_FILE).read().strip()
19 except IOError:
20 try:
21 import random
22 SECRET_KEY = ''.join([random.SystemRandom().choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)])
23 secret = file(SECRET_FILE, 'w')
24 secret.write(SECRET_KEY)
25 secret.close()
26 except IOError:
27 Exception('Please create a %s file with random characters \
28 to generate your secret key!' % SECRET_FILE)