Skip to content

Instantly share code, notes, and snippets.

@xianyunwuxin
Created December 4, 2014 18:39
Show Gist options
  • Save xianyunwuxin/5ae664ce6f8b3f6b7878 to your computer and use it in GitHub Desktop.
Save xianyunwuxin/5ae664ce6f8b3f6b7878 to your computer and use it in GitHub Desktop.
like Mongodb's ObjectID
# coding:utf8
# object_id.py
__all__ = ('ObjectID', )
from __future__ import print_function
from __future__ import unicode_literals
import os
import struct
import socket
import sys
from hashlib import md5
import time
import itertools
import binascii
PY3 = sys.version_info[0] == 3
def _object_id():
range_ = range
if not PY3:
range_ = xrange
iter_ = itertools.cycle(range_(0xffffff))
machine = md5(socket.gethostname().encode('utf8')).digest()[:3]
pid = struct.pack('>L', os.getpid())
def f(as_bytes=False):
now = struct.pack('>L', int(time.time()))
inc = struct.pack('>L', next(iter_))[1:]
result = b''.join(
(now, machine, pid, inc)
)
return result
return f
object_id = _object_id()
class ObjectID(object):
def __init__(self, val=None):
if not val:
self.bytes = object_id()
elif type(val) is bytes:
self.bytes = val
else:
self.string = val
@property
def string(self):
return self._string
@string.setter
def string(self, val):
self._string = val
self._bytes = binascii.unhexlify(val)
@property
def bytes(self):
return self._bytes
@bytes.setter
def bytes(self, val):
self._bytes = val
self._string = binascii.hexlify(val).decode('utf8')
def __str__(self):
return self.string
if PY3:
def __eq__(self, b):
return self.bytes == b.bytes
else:
def __cmp__(self, b):
return not self.bytes == b.bytes
if __name__ == '__main__':
a = ObjectID()
b = ObjectID(a.string)
c = ObjectID(a.bytes)
print(a==b)
print(a==c)
d = ObjectID()
print(a==d)
list(map(print, (a, b, c, d)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment