Skip to content

Instantly share code, notes, and snippets.

@dpk
Last active December 19, 2015 22:59
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 dpk/6031230 to your computer and use it in GitHub Desktop.
Save dpk/6031230 to your computer and use it in GitHub Desktop.
Python: compact-ish unique identifiers
import base64
import struct
from uuid import getnode as get_mac
import os
from threading import Lock
import time
from ssl import RAND_bytes as random_bytes
mac = struct.pack('>Q', get_mac())[2:] # do this now in case it is slow (see Python manual)
count = 0
count_lock = Lock()
def generate():
global count
our_count = 0
with count_lock:
count += 1
our_count = count
return base64.urlsafe_b64encode(mac + struct.pack('>dLH', time.time(), os.getpid(), (our_count % (2 ** 16))) + random_bytes(4))
@dpk
Copy link
Author

dpk commented Jan 26, 2015

updated 2014-01: change the order of the components which are output so as to result in less fragmentation when the IDs are used as keys in a B-Tree like data structure

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