Skip to content

Instantly share code, notes, and snippets.

@socketz
Created September 2, 2021 05:54
Show Gist options
  • Save socketz/cdc8e2fab2c5f87ab300f672a37f6626 to your computer and use it in GitHub Desktop.
Save socketz/cdc8e2fab2c5f87ab300f672a37f6626 to your computer and use it in GitHub Desktop.
Generates a random secret key for Django or other kind projects.
#!/usr/bin/env python3
import secrets
import sys
import os
import argparse
RANDOM_STRING_CHARS = '''abcdefghijklmnñopqrstuvwxyzçáéíóúäëïöüâêîôûàèìòùåõýÿABCDEFGHIJKLMNÑOPQRSTUVWXYZÇÁÉÍÓÚÄËÏÖÜÂÊÎÔÛÀÈÌÒÙ0123456789!@$€¢¥£%^&*(-_=+)?¿¡^`´¬|~;,.·<>'"[]{}¨ƒ…†‡ˆ‰šžŠŽ‹›Œœ#«»ºª°±µÐæÆþ'''
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
RESET_BOLD = '\033[21m'
DIM = '\033[2m'
RESET_DIM = '\033[22m'
ITALIC = '\033[3m'
RESET_ITALIC = '\033[23m'
UNDERLINE = '\033[4m'
RESET_UNDERLINE = '\033[24m'
REVERSE = '\033[7m'
RESET_REVERSE = '\033[27m'
HIDDEN = '\033[8m'
RESET_HIDDEN = '\033[28m'
STRIKETHROUGH = '\033[9m'
RESET_STRIKETHROUGH = '\033[29m'
def supports_color():
"""
Returns True if the running system's terminal supports color, and False
otherwise.
"""
def vt_codes_enabled_in_windows_registry():
"""
Check the Windows Registry to see if VT code handling has been enabled
by default, see https://superuser.com/a/1300251/447564.
"""
try:
# winreg is only available on Windows.
import winreg
except ImportError:
return False
else:
reg_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, 'Console')
try:
reg_key_value, _ = winreg.QueryValueEx(
reg_key, 'VirtualTerminalLevel')
except FileNotFoundError:
return False
else:
return reg_key_value == 1
supported_platform = (
sys.platform != 'win32' or 'ANSICON' in os.environ or
# Windows Terminal supports VT codes.
'WT_SESSION' in os.environ or
# Microsoft Visual Studio Code's built-in terminal supports colors.
os.environ.get('TERM_PROGRAM') == 'vscode' or
vt_codes_enabled_in_windows_registry()
)
# isatty is not always implemented, #6223.
is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()
return supported_platform and is_a_tty
def get_random_string(length, allowed_chars=RANDOM_STRING_CHARS):
return (''.join(secrets.choice(allowed_chars) for i in range(length))).strip()
def generate_secret_key(length: int = 50):
"""
Returns a 50 character random string usable as a `SECRET_KEY` setting value.
"""
if not isinstance(length, int):
raise TypeError(
f'invalid literal for int() with base 10: {length}')
return get_random_string(length)
def main(length=50):
if bcolors.supports_color():
message = f"{bcolors.BOLD}{generate_secret_key(length)}{bcolors.ENDC}"
else:
message = generate_secret_key(length)
print(f"{bcolors.OKGREEN}Your secret key:{bcolors.ENDC}", message, "\n")
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description='Generates a random secret key for Django or other kind projects using UTF-8 charset.')
parser.add_argument('length', type=int, nargs='?',
default=50, help='an integer for length to generate')
parser.add_argument('-n', dest='no_colors',
action='store_true', help='disable output colors')
args = parser.parse_args()
length = args.length
generic_msg = 'Your secret key: '
if bcolors.supports_color() and args.no_colors is False:
message = f"{bcolors.OKGREEN}{generic_msg}{bcolors.ENDC}{bcolors.BOLD}{generate_secret_key(length)}{bcolors.ENDC}\n"
else:
message = f"{generic_msg}{generate_secret_key(length)}\n"
print(message)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment