From: Javier Sancho Date: Mon, 17 Mar 2014 16:03:39 +0000 (+0100) Subject: Introducing ObjectId X-Git-Url: https://git.jsancho.org/?p=mojodb.git;a=commitdiff_plain;h=aa9319f8b2c7aa4f49f5ab90b1fdd66efccb3a50 Introducing ObjectId --- diff --git a/collection.py b/collection.py index e0f0002..b8d51a0 100644 --- a/collection.py +++ b/collection.py @@ -20,7 +20,7 @@ ############################################################################## from cursor import Cursor -import uuid +from objectid import ObjectId class Collection(object): def __init__(self, database, table_name): @@ -63,7 +63,7 @@ class Collection(object): else: docs = doc_or_docs for doc in docs: - doc_id = uuid.uuid4().hex + doc_id = str(ObjectId()) if not '_id' in doc: doc['_id'] = doc_id self._insert_document(doc_id, doc) 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),)