· 7 years ago · Jul 05, 2018, 01:46 PM
1#!/usr/bin/env python3
2
3import random
4
5
6def get_random_string(length=12,
7 allowed_chars='abcdefghijklmnopqrstuvwxyz'
8 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
9 """
10 Return a securely generated random string.
11 The default length of 12 with the a-z, A-Z, 0-9 character set returns
12 a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
13 """
14 return ''.join(random.SystemRandom().choice(allowed_chars) for i in range(length))
15
16
17def get_random_secret_key():
18 """
19 Return a 50 character random string usable as a SECRET_KEY setting value.
20 """
21 chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
22 return get_random_string(50, chars)
23
24
25print(get_random_secret_key())