Skip to content

Instantly share code, notes, and snippets.

@dob9601
Last active July 4, 2018 21:01
Show Gist options
  • Save dob9601/106e0de7c92add5089a3572c1edb885f to your computer and use it in GitHub Desktop.
Save dob9601/106e0de7c92add5089a3572c1edb885f to your computer and use it in GitHub Desktop.
Random generation for django SECRET_KEY variable designed for GitHub projects - remove the declaration of the SECRET_KEY in settings.py and replace it with this. Upon the webapp first being run, a file named SECRET_KEY is created in the <project_name> folder. This removes the risk of someone downloading a project without then forgetting to adjus…
import random
import string
try:
with open('<PROJECT_NAME>/SECRET_KEY', 'r') as secret_key_file:
SECRET_KEY = secret_key_file.read()
if SECRET_KEY == '':
raise FileNotFoundError
except FileNotFoundError:
with open('<PROJECT_NAME>/SECRET_KEY', 'w') as secret_key_file:
chars = ''.join([string.ascii_letters, string.digits, string.punctuation]).replace('\'', '').replace('"', '').replace('\\', '')
SECRET_KEY = ''.join([random.SystemRandom().choice(chars) for i in range(50)])
secret_key_file.write(SECRET_KEY)
secret_key_file.close()
@dob9601
Copy link
Author

dob9601 commented Jul 4, 2018

Ensure that you replace <PROJECT_NAME> with the name of your project

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