Skip to content

Instantly share code, notes, and snippets.

@mjallday
Created May 7, 2015 22:55
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 mjallday/f56ce230cfef4b8143c4 to your computer and use it in GitHub Desktop.
Save mjallday/f56ce230cfef4b8143c4 to your computer and use it in GitHub Desktop.
Balanced ID Generator
def id_factory(prefix=None):
def generate():
bytes_ = hashlib.sha1(uuid.uuid1().bytes).digest()
# base62_encode comes from
# https://stackoverflow.com/questions/1119722/base-62-conversion-in-python
id_ = base62_encode(int(bytes_.encode('hex'), base=16))[:12]
if prefix:
id_ = prefix + id_
return id_
return generate
def eid_factory(prefix=None, alphanum=True):
"""
Given a prefix, which defaults to None, will generate a function
which when called, will generate a 10 character id using random() and
format it as [{prefix}]{xxx}-{xxx}-{xxxx}.
"""
def generate_eid():
valid_chars = string.digits
if alphanum:
valid_chars += string.ascii_uppercase
the_eid = ''.join(random.choice(valid_chars) for _ in xrange(10))
the_eid = '-'.join([the_eid[0:3], the_eid[3:6], the_eid[6:]])
if prefix:
the_eid = prefix + the_eid
return the_eid
return generate_eid
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment