X-Git-Url: https://git.jsancho.org/?p=mojodb.git;a=blobdiff_plain;f=objectid.py;fp=objectid.py;h=0bf05c0d7fcf6003987fec33d1bcc60985ac145f;hp=0000000000000000000000000000000000000000;hb=aa9319f8b2c7aa4f49f5ab90b1fdd66efccb3a50;hpb=71d218d3b08766a0bba066080d0d8fc3bd3705a8 diff --git a/objectid.py b/objectid.py new file mode 100644 index 0000000..0bf05c0 --- /dev/null +++ b/objectid.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# mojo, a Python library for implementing document based databases +# Copyright (C) 2013-2014 by Javier Sancho Fernandez +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## + +import binascii +import hashlib +import os +import random +import socket +import struct +import time +import threading + +class ObjectId(object): + _inc = random.randint(0, 0xFFFFFF) + _inc_lock = threading.Lock() + + __id = "" + + def __init__(self): + self.__generate() + + def __generate(self): + oid = "" + # Secons since the Unix epoch + oid += struct.pack(">i", int(time.time())) + # Machine Identifier + machine_hash = hashlib.md5() + machine_hash.update(socket.gethostname()) + oid += machine_hash.digest()[0:3] + # Process Id + oid += struct.pack(">H", os.getpid() % 0xFFFF) + # Counter + ObjectId._inc_lock.acquire() + oid += struct.pack(">i", ObjectId._inc)[1:4] + ObjectId._inc += 1 + ObjectId._inc_lock.release() + + self.__id = oid + + def __str__(self): + return binascii.hexlify(self.__id) + + def __repr__(self): + return "ObjectId('%s')" % (str(self),)