Skip to content

Commit 1ef67de

Browse files
committed
Command to generate a secret key for Django.
1 parent 834bff0 commit 1ef67de

3 files changed

Lines changed: 39 additions & 2 deletions

File tree

comics/management/commands/__init__.py

Whitespace-only changes.
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
from __future__ import unicode_literals
2+
3+
import os, re
4+
import tenma
5+
6+
from django.conf import settings
7+
from django.core import management
8+
from django.utils.crypto import get_random_string
9+
from shutil import copyfile, move
10+
11+
BASE_DIR = os.path.dirname(tenma.__file__)
12+
13+
class Command(management.BaseCommand):
14+
help = 'Generates a random secret key.'
15+
16+
@staticmethod
17+
def _generate_secret_key():
18+
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_=+[\{]\{;:,<.>/?'
19+
return get_random_string(50, chars)
20+
21+
def handle(self, *args, **options):
22+
orig = os.path.join(BASE_DIR, 'settings.py')
23+
temp = os.path.join(BASE_DIR, 'temp.py')
24+
copyfile(orig, temp)
25+
26+
with open(temp, 'w') as new_file:
27+
with open(orig) as old_file:
28+
for line in old_file:
29+
secret_key = re.match(r'^SECRET_KEY ?=', line)
30+
if secret_key:
31+
line = "SECRET_KEY = '{0}'".format(Command._generate_secret_key()) + '\n'
32+
new_file.write(line)
33+
34+
new_file.close()
35+
os.remove(orig)
36+
os.rename(temp, orig)

tenma/settings.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,15 @@
2020
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/
2121

2222
# SECURITY WARNING: keep the secret key used in production secret!
23-
SECRET_KEY = 'v0v)u49dj#c6vdnr9a5fl*mv$=9b3n#y=_f#frz^x-cqg*#pe_'
23+
# To generate a SECRET_KEY, use The following command:
24+
# python manage.py generatesecretkey
25+
SECRET_KEY = '<secret-key>'
2426

2527
# SECURITY WARNING: don't run with debug turned on in production!
2628
DEBUG = True
2729

2830
ALLOWED_HOSTS = []
2931

30-
3132
# Application definition
3233

3334
INSTALLED_APPS = [

0 commit comments

Comments
 (0)