Instantly share code, notes, and snippets.

Embed
What would you like to do?
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`.
"""
try:
SECRET_KEY
except NameError:
SECRET_FILE = os.path.join(PROJECT_PATH, '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)
@ndarville

This comment has been minimized.

Owner

ndarville commented Sep 4, 2012

To see a working example, feel free to git clone my pony-forum repo or deploy it on dotCloud.

@ErikEvenson

This comment has been minimized.

ErikEvenson commented Jun 18, 2013

This is great, but won't work with PaaS providers like Heroku where the file system is ephemeral. In those cases, modifying this gist to save the secret in a environment variable would fix the issue.

@SEJeff

This comment has been minimized.

SEJeff commented Dec 27, 2013

May I suggest using string.printable instead of a hardcoded list of printable characters?

@electroniceagle

This comment has been minimized.

electroniceagle commented Jan 13, 2014

I think string printable includes carriage return and tab.

@SEJeff

This comment has been minimized.

SEJeff commented Feb 17, 2014

Ok then may I suggest this version instead:

SECRET_KEY = ''.join([random.SystemRandom().choice("{}{}{}".format(string.ascii_letters, string.digits, string.punctuation)) for i in range(50)])
@billmei

This comment has been minimized.

billmei commented Apr 5, 2014

I made a fork that works on a cloud provider like Heroku:

import os

"""
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 gets an environment variable `DJANGO_SECRET_KEY`

The result is a random and safely hidden `SECRET_KEY`.
"""
try:
    SECRET_KEY
except NameError:
    SECRET_FILE = os.path.join(PROJECT_DIR, 'secret.txt')
    try:
        SECRET_KEY = open(SECRET_FILE).read().strip()
    except IOError:
        SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')
@habibalamin

This comment has been minimized.

habibalamin commented May 15, 2014

Why does this try to evaluate SECRET_KEY first? It's not defined anywhere.

@pnovotnak

This comment has been minimized.

pnovotnak commented Jul 23, 2014

If you are using this on a server that runs multiple apps as different UIDs, you should think about setting the permissions bits 0600

@croepha

This comment has been minimized.

croepha commented Jul 31, 2015

Here is a one-liner, that will print to the console:

function mk_dj_secret() { python -c "import random,string;print 'SECRET_KEY=\"%s\"'%''.join([random.SystemRandom().choice(\"{}{}{}\".format(string.ascii_letters, string.digits, string.punctuation)) for i in range(63)])" ;}

you can pipe that to an .env file or a settings.py file:

mk_dj_secret  >> ~/secrets/my_app.env

This is what I use when deploying with docker, and I use decouple in my settings.py

@fjsj

This comment has been minimized.

fjsj commented Aug 26, 2016

For setting SECRET_KEY env var on Heroku in a single line:

heroku config:set SECRET_KEY=$(python -c 'import random; import string; print("".join([random.SystemRandom().choice("{}{}{}".format(string.ascii_letters, string.digits, string.punctuation)) for i in range(50)]))')
@jrial

This comment has been minimized.

jrial commented Dec 27, 2016

@SEJeff: he is using that particular set of characters because that's the one used by the original function get_random_secret_key(). See line 86 on https://github.com/django/django/blob/3c447b108ac70757001171f7a4791f493880bf5b/django/core/management/utils.py

For starters, notice how there are no capital letters in the original set. So that means you can not use string.ascii_letters, but have to use string.ascii_lowercase instead. Then take a look at the part past the integers. There are 14 "punctuation" characters there, while string.punctuation contains 32.

Your suggestion might work, or it might not. I don't know enough about cryptography nor how the SECRET_KEY is used throughout Django. But it's not a drop-in replacement since it will not generate keys containing the same set of characters.

@antonagestam

This comment has been minimized.

antonagestam commented Sep 15, 2017

Actually, Django is using the exact same method to derive the secret key as this snippet and has been since at least 2012 https://github.com/django/django/blame/3c447b108ac70757001171f7a4791f493880bf5b/django/utils/crypto.py#L20

@dongyuzheng

This comment has been minimized.

dongyuzheng commented Nov 14, 2017

Properly escaped:

function django_secret() { python -c "import random,string;print(''.join([random.SystemRandom().choice(\"{}{}{}\".format(string.ascii_letters, string.digits, string.punctuation)) for i in range(63)]).replace('\\'','\\'\"\\'\"\\''))"; }
echo "DJANGO_SECRET_KEY='$(django_secret)'"
@tjps

This comment has been minimized.

tjps commented Jan 15, 2018

Simplest and most accurate way is to just use the function in Django directly:

python manage.py shell -c 'from django.core.management import utils; print(utils.get_random_secret_key())'
@hseritt

This comment has been minimized.

hseritt commented Mar 2, 2018

Thanks tjps ... using that in my app.

@dnintzel

This comment has been minimized.

dnintzel commented Mar 30, 2018

Is secret-key-gen.py intended to be a one-time generator or would you possibly call at boot time to generate new key? I don't use heroku/(ephemeral fs), but maybe that usage would solve that issue too?

...or generating with any method including tjps' suggestion?

[update] One bad side affect to new secret key is credentials are lost and forces re-authentication (if used).

@MavropaliasG

This comment has been minimized.

MavropaliasG commented May 7, 2018

Hi everyone, I'm very interesting to try that in our django project Epitome.

@ndarville, @SEJeff and everyone thank you for writing this code.

The reason I need this is because I am developing a script to automate installation in linux distributions. The problem is that I haven't found a way to automate the creation of a unique secret key.

I know I'm asking for a lot, but if someone could someone create a pull request to our settings.py file with a script that will automatically create a secret key regardless of being in linux or windows and with the user not having to do anything further, I will be extremely grateful. I have tried implementing the code snippets here but with no success.

Please send me a message if you would like to discuss further, I will be happy to hear from you.

@andytwoods

This comment has been minimized.

andytwoods commented May 29, 2018

in windows python manage.py shell -c "from django.core.management import utils; print(utils.get_random_secret_key())" (nb double not single quotes)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment