Create a strong password in Python/Django

Tags: utils

The utility function below creates strong random passwords.  They are suitable for a Django project's SECRET_KEY setting, as well as things like database passwords or new users' passwords...


import string
import random

def new_password(length=50):
    # a django SECRET_KEY should be 50 chars
    chars = set(string.ascii_letters + string.digits + string.punctuation)
    not_use = ('"', "'", '=', '`', '\\')
    use = list(chars.difference(not_use))
    password = [random.SystemRandom().choice(use) for i in range(length)]
    return "".join(password)
    

The password is created out of upper and lower case letters, digits and punctuation.  I exclude several punctation characters - things like backslashes and single/double quotes are a pain to use in strings :-) 


# output of string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

# output of string.digits
'0123456789'

# output of string.punctation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
    
Loading comments...
';