Last active
December 19, 2015 22:59
-
-
Save dpk/6031230 to your computer and use it in GitHub Desktop.
Python: compact-ish unique identifiers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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