Skip to content

Instantly share code, notes, and snippets.

@lym
Forked from ndarville/secret-key-gen.py
Created September 23, 2020 14:30
Show Gist options
  • Select an option

  • Save lym/c79fea07ae6ad7e85b64e61ef29eaf17 to your computer and use it in GitHub Desktop.

Select an option

Save lym/c79fea07ae6ad7e85b64e61ef29eaf17 to your computer and use it in GitHub Desktop.

Revisions

  1. @ndarville ndarville created this gist Aug 24, 2012.
    28 changes: 28 additions & 0 deletions secret-key-gen.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    """
    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)