Skip to content

Instantly share code, notes, and snippets.

@wonderbeyond
Last active September 16, 2019 05:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wonderbeyond/1806c7b43d3e642e5ad0aee7052b8e8f to your computer and use it in GitHub Desktop.
Save wonderbeyond/1806c7b43d3e642e5ad0aee7052b8e8f to your computer and use it in GitHub Desktop.
Get a secret random string in python(Refer to django.utils.crypto.get_random_string)
import os
import binascii
import uuid
from xid import Xid
def get_guid(style='uuid'):
"""Get a globally unique string for identify things"""
if style == 'uuid':
return uuid.uuid4().hex
if style == 'xid':
return Xid().string()
raise RuntimeError('Unsupported guid style: {0}'.format(style))
# Equivalent implementation
def get_guid():
return binascii.hexlify(os.urandom(16)).decode()
import random
import hashlib
import time
def get_random_string(length=12,
allowed_chars='abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
"""
See also:
https://github.com/rs/xid (globally unique id generator)
https://stackoverflow.com/questions/41354205/how-to-generate-a-unique-auth-token-in-python
https://docs.python.org/3/whatsnew/3.6.html#secrets
"""
random.seed(
hashlib.sha256(
("%s%s%s" % (
random.getstate(),
time.time(),
'O_O-SECRET_KEY')).encode('utf-8')
).digest())
return ''.join(random.choice(allowed_chars) for i in range(length))
# --- Simple One ---
import string
import random
def get_random_string(N=12, allowed_chars=(string.ascii_letters + string.digits)):
return ''.join(random.choice(allowed_chars) for _ in range(N))
@fxyzbtc
Copy link

fxyzbtc commented Sep 12, 2019

def get_random_string(N=12, allowed_chars=(string.ascii_letters + string.digits)):
    return ''.join(random.choice(allowed_chars) for _ in range(N))

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