A MongoDB ObjectId.
| 46 | |
| 47 | |
| 48 | class ObjectId: |
| 49 | """A MongoDB ObjectId.""" |
| 50 | |
| 51 | _pid = os.getpid() |
| 52 | |
| 53 | _inc = SystemRandom().randint(0, _MAX_COUNTER_VALUE) |
| 54 | _inc_lock = threading.Lock() |
| 55 | |
| 56 | __random = _random_bytes() |
| 57 | |
| 58 | __slots__ = ("__id",) |
| 59 | |
| 60 | _type_marker = 7 |
| 61 | |
| 62 | def __init__(self, oid: Optional[Union[str, ObjectId, bytes]] = None) -> None: |
| 63 | """Initialize a new ObjectId. |
| 64 | |
| 65 | An ObjectId is a 12-byte unique identifier consisting of: |
| 66 | |
| 67 | - a 4-byte value representing the seconds since the Unix epoch, |
| 68 | - a 5-byte random value, |
| 69 | - a 3-byte counter, starting with a random value. |
| 70 | |
| 71 | By default, ``ObjectId()`` creates a new unique identifier. The |
| 72 | optional parameter `oid` can be an :class:`ObjectId`, or any 12 |
| 73 | :class:`bytes`. |
| 74 | |
| 75 | For example, the 12 bytes b'foo-bar-quux' do not follow the ObjectId |
| 76 | specification but they are acceptable input:: |
| 77 | |
| 78 | >>> ObjectId(b'foo-bar-quux') |
| 79 | ObjectId('666f6f2d6261722d71757578') |
| 80 | |
| 81 | `oid` can also be a :class:`str` of 24 hex digits:: |
| 82 | |
| 83 | >>> ObjectId('0123456789ab0123456789ab') |
| 84 | ObjectId('0123456789ab0123456789ab') |
| 85 | |
| 86 | Raises :class:`~bson.errors.InvalidId` if `oid` is not 12 bytes nor |
| 87 | 24 hex digits, or :class:`TypeError` if `oid` is not an accepted type. |
| 88 | |
| 89 | :param oid: a valid ObjectId. |
| 90 | |
| 91 | .. seealso:: The MongoDB documentation on `ObjectIds <http://dochub.mongodb.org/core/objectids>`_. |
| 92 | |
| 93 | .. versionchanged:: 3.8 |
| 94 | :class:`~bson.objectid.ObjectId` now implements the `ObjectID |
| 95 | specification version 0.2 |
| 96 | <https://github.com/mongodb/specifications/blob/master/source/ |
| 97 | objectid.rst>`_. |
| 98 | """ |
| 99 | if oid is None: |
| 100 | # Generate a new value for this ObjectId. |
| 101 | with ObjectId._inc_lock: |
| 102 | inc = ObjectId._inc |
| 103 | ObjectId._inc = (inc + 1) % (_MAX_COUNTER_VALUE + 1) |
| 104 | |
| 105 | # 4 bytes current time, 5 bytes random, 3 bytes inc. |