Skip to content

Instantly share code, notes, and snippets.

@dpk dpk/uniqid.py
Last active Dec 19, 2015

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

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
You can’t perform that action at this time.