Last active
June 28, 2018 02:54
-
-
Save airtonix/6204802 to your computer and use it in GitHub Desktop.
Django Settings. Dynamic secret key. Keep your secret key out of version control.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from hashlib import md5, sha1 | |
from base64 import urlsafe_b64encode as b64encode | |
import random, string | |
random.seed() | |
pattern = "%%0%dX" | |
junk_len = 1024 | |
def generate_key(max_length, seed_length, encoder=b64encode, digester=sha1): | |
""" | |
Generate a Base64-encoded 'random' key by hashing the data. | |
data is a tuple of seeding values. Pass arbitrary encoder and | |
digester for specific hashing and formatting of keys | |
""" | |
junk = ( pattern % (junk_len * 2) ) % random.getrandbits( junk_len * seed_length ) | |
key = str(junk).encode() | |
return b64encode( key )[:max_length] | |
def random_hash(): | |
return generate_key(96,1024,digester=sha1) | |
if __name__ == "__main__" : | |
for count in range(150) : | |
print random_hash() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# Automatically Build a Secret Key | |
# | |
# We do this so we can put base/settings/key.py into .gitignore for this project template. | |
# You'd obviously remove that constraint for your own projects. | |
try: | |
from .key import * | |
except ImportError: | |
from base.lib.generate_key import generate_key | |
secret_key_file = open(os.path.join(HERE_DIR, "key.py"), "w") | |
secret_key_file.write("""SECRET_KEY = "{0}" """.format(generate_key(40, 128))) | |
secret_key_file.close() | |
from .key import * |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment