Initial commit
This commit is contained in:
1273
venv/lib/python3.8/site-packages/bson/__init__.py
Normal file
1273
venv/lib/python3.8/site-packages/bson/__init__.py
Normal file
File diff suppressed because it is too large
Load Diff
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
venv/lib/python3.8/site-packages/bson/_cbson.cpython-38-x86_64-linux-gnu.so
Executable file
BIN
venv/lib/python3.8/site-packages/bson/_cbson.cpython-38-x86_64-linux-gnu.so
Executable file
Binary file not shown.
245
venv/lib/python3.8/site-packages/bson/binary.py
Normal file
245
venv/lib/python3.8/site-packages/bson/binary.py
Normal file
@@ -0,0 +1,245 @@
|
||||
# Copyright 2009-present MongoDB, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from uuid import UUID
|
||||
|
||||
from bson.py3compat import PY3
|
||||
|
||||
"""Tools for representing BSON binary data.
|
||||
"""
|
||||
|
||||
BINARY_SUBTYPE = 0
|
||||
"""BSON binary subtype for binary data.
|
||||
|
||||
This is the default subtype for binary data.
|
||||
"""
|
||||
|
||||
FUNCTION_SUBTYPE = 1
|
||||
"""BSON binary subtype for functions.
|
||||
"""
|
||||
|
||||
OLD_BINARY_SUBTYPE = 2
|
||||
"""Old BSON binary subtype for binary data.
|
||||
|
||||
This is the old default subtype, the current
|
||||
default is :data:`BINARY_SUBTYPE`.
|
||||
"""
|
||||
|
||||
OLD_UUID_SUBTYPE = 3
|
||||
"""Old BSON binary subtype for a UUID.
|
||||
|
||||
:class:`uuid.UUID` instances will automatically be encoded
|
||||
by :mod:`bson` using this subtype.
|
||||
|
||||
.. versionadded:: 2.1
|
||||
"""
|
||||
|
||||
UUID_SUBTYPE = 4
|
||||
"""BSON binary subtype for a UUID.
|
||||
|
||||
This is the new BSON binary subtype for UUIDs. The
|
||||
current default is :data:`OLD_UUID_SUBTYPE`.
|
||||
|
||||
.. versionchanged:: 2.1
|
||||
Changed to subtype 4.
|
||||
"""
|
||||
|
||||
STANDARD = UUID_SUBTYPE
|
||||
"""The standard UUID representation.
|
||||
|
||||
:class:`uuid.UUID` instances will automatically be encoded to
|
||||
and decoded from BSON binary, using RFC-4122 byte order with
|
||||
binary subtype :data:`UUID_SUBTYPE`.
|
||||
|
||||
.. versionadded:: 3.0
|
||||
"""
|
||||
|
||||
PYTHON_LEGACY = OLD_UUID_SUBTYPE
|
||||
"""The Python legacy UUID representation.
|
||||
|
||||
:class:`uuid.UUID` instances will automatically be encoded to
|
||||
and decoded from BSON binary, using RFC-4122 byte order with
|
||||
binary subtype :data:`OLD_UUID_SUBTYPE`.
|
||||
|
||||
.. versionadded:: 3.0
|
||||
"""
|
||||
|
||||
JAVA_LEGACY = 5
|
||||
"""The Java legacy UUID representation.
|
||||
|
||||
:class:`uuid.UUID` instances will automatically be encoded to
|
||||
and decoded from BSON binary subtype :data:`OLD_UUID_SUBTYPE`,
|
||||
using the Java driver's legacy byte order.
|
||||
|
||||
.. versionchanged:: 3.6
|
||||
BSON binary subtype 4 is decoded using RFC-4122 byte order.
|
||||
.. versionadded:: 2.3
|
||||
"""
|
||||
|
||||
CSHARP_LEGACY = 6
|
||||
"""The C#/.net legacy UUID representation.
|
||||
|
||||
:class:`uuid.UUID` instances will automatically be encoded to
|
||||
and decoded from BSON binary subtype :data:`OLD_UUID_SUBTYPE`,
|
||||
using the C# driver's legacy byte order.
|
||||
|
||||
.. versionchanged:: 3.6
|
||||
BSON binary subtype 4 is decoded using RFC-4122 byte order.
|
||||
.. versionadded:: 2.3
|
||||
"""
|
||||
|
||||
ALL_UUID_SUBTYPES = (OLD_UUID_SUBTYPE, UUID_SUBTYPE)
|
||||
ALL_UUID_REPRESENTATIONS = (STANDARD, PYTHON_LEGACY, JAVA_LEGACY, CSHARP_LEGACY)
|
||||
UUID_REPRESENTATION_NAMES = {
|
||||
PYTHON_LEGACY: 'PYTHON_LEGACY',
|
||||
STANDARD: 'STANDARD',
|
||||
JAVA_LEGACY: 'JAVA_LEGACY',
|
||||
CSHARP_LEGACY: 'CSHARP_LEGACY'}
|
||||
|
||||
MD5_SUBTYPE = 5
|
||||
"""BSON binary subtype for an MD5 hash.
|
||||
"""
|
||||
|
||||
USER_DEFINED_SUBTYPE = 128
|
||||
"""BSON binary subtype for any user defined structure.
|
||||
"""
|
||||
|
||||
|
||||
class Binary(bytes):
|
||||
"""Representation of BSON binary data.
|
||||
|
||||
This is necessary because we want to represent Python strings as
|
||||
the BSON string type. We need to wrap binary data so we can tell
|
||||
the difference between what should be considered binary data and
|
||||
what should be considered a string when we encode to BSON.
|
||||
|
||||
Raises TypeError if `data` is not an instance of :class:`bytes`
|
||||
(:class:`str` in python 2) or `subtype` is not an instance of
|
||||
:class:`int`. Raises ValueError if `subtype` is not in [0, 256).
|
||||
|
||||
.. note::
|
||||
In python 3 instances of Binary with subtype 0 will be decoded
|
||||
directly to :class:`bytes`.
|
||||
|
||||
:Parameters:
|
||||
- `data`: the binary data to represent. Can be any bytes-like type
|
||||
that implements the buffer protocol.
|
||||
- `subtype` (optional): the `binary subtype
|
||||
<http://bsonspec.org/#/specification>`_
|
||||
to use
|
||||
|
||||
.. versionchanged:: 3.9
|
||||
Support any bytes-like type that implements the buffer protocol.
|
||||
"""
|
||||
|
||||
_type_marker = 5
|
||||
|
||||
def __new__(cls, data, subtype=BINARY_SUBTYPE):
|
||||
if not isinstance(subtype, int):
|
||||
raise TypeError("subtype must be an instance of int")
|
||||
if subtype >= 256 or subtype < 0:
|
||||
raise ValueError("subtype must be contained in [0, 256)")
|
||||
# Support any type that implements the buffer protocol.
|
||||
self = bytes.__new__(cls, memoryview(data).tobytes())
|
||||
self.__subtype = subtype
|
||||
return self
|
||||
|
||||
@property
|
||||
def subtype(self):
|
||||
"""Subtype of this binary data.
|
||||
"""
|
||||
return self.__subtype
|
||||
|
||||
def __getnewargs__(self):
|
||||
# Work around http://bugs.python.org/issue7382
|
||||
data = super(Binary, self).__getnewargs__()[0]
|
||||
if PY3 and not isinstance(data, bytes):
|
||||
data = data.encode('latin-1')
|
||||
return data, self.__subtype
|
||||
|
||||
def __eq__(self, other):
|
||||
if isinstance(other, Binary):
|
||||
return ((self.__subtype, bytes(self)) ==
|
||||
(other.subtype, bytes(other)))
|
||||
# We don't return NotImplemented here because if we did then
|
||||
# Binary("foo") == "foo" would return True, since Binary is a
|
||||
# subclass of str...
|
||||
return False
|
||||
|
||||
def __hash__(self):
|
||||
return super(Binary, self).__hash__() ^ hash(self.__subtype)
|
||||
|
||||
def __ne__(self, other):
|
||||
return not self == other
|
||||
|
||||
def __repr__(self):
|
||||
return "Binary(%s, %s)" % (bytes.__repr__(self), self.__subtype)
|
||||
|
||||
|
||||
class UUIDLegacy(Binary):
|
||||
"""UUID wrapper to support working with UUIDs stored as PYTHON_LEGACY.
|
||||
|
||||
.. doctest::
|
||||
|
||||
>>> import uuid
|
||||
>>> from bson.binary import Binary, UUIDLegacy, STANDARD
|
||||
>>> from bson.codec_options import CodecOptions
|
||||
>>> my_uuid = uuid.uuid4()
|
||||
>>> coll = db.get_collection('test',
|
||||
... CodecOptions(uuid_representation=STANDARD))
|
||||
>>> coll.insert_one({'uuid': Binary(my_uuid.bytes, 3)}).inserted_id
|
||||
ObjectId('...')
|
||||
>>> coll.count_documents({'uuid': my_uuid})
|
||||
0
|
||||
>>> coll.count_documents({'uuid': UUIDLegacy(my_uuid)})
|
||||
1
|
||||
>>> coll.find({'uuid': UUIDLegacy(my_uuid)})[0]['uuid']
|
||||
UUID('...')
|
||||
>>>
|
||||
>>> # Convert from subtype 3 to subtype 4
|
||||
>>> doc = coll.find_one({'uuid': UUIDLegacy(my_uuid)})
|
||||
>>> coll.replace_one({"_id": doc["_id"]}, doc).matched_count
|
||||
1
|
||||
>>> coll.count_documents({'uuid': UUIDLegacy(my_uuid)})
|
||||
0
|
||||
>>> coll.count_documents({'uuid': {'$in': [UUIDLegacy(my_uuid), my_uuid]}})
|
||||
1
|
||||
>>> coll.find_one({'uuid': my_uuid})['uuid']
|
||||
UUID('...')
|
||||
|
||||
Raises TypeError if `obj` is not an instance of :class:`~uuid.UUID`.
|
||||
|
||||
:Parameters:
|
||||
- `obj`: An instance of :class:`~uuid.UUID`.
|
||||
"""
|
||||
|
||||
def __new__(cls, obj):
|
||||
if not isinstance(obj, UUID):
|
||||
raise TypeError("obj must be an instance of uuid.UUID")
|
||||
self = Binary.__new__(cls, obj.bytes, OLD_UUID_SUBTYPE)
|
||||
self.__uuid = obj
|
||||
return self
|
||||
|
||||
def __getnewargs__(self):
|
||||
# Support copy and deepcopy
|
||||
return (self.__uuid,)
|
||||
|
||||
@property
|
||||
def uuid(self):
|
||||
"""UUID instance wrapped by this UUIDLegacy instance.
|
||||
"""
|
||||
return self.__uuid
|
||||
|
||||
def __repr__(self):
|
||||
return "UUIDLegacy('%s')" % self.__uuid
|
||||
99
venv/lib/python3.8/site-packages/bson/code.py
Normal file
99
venv/lib/python3.8/site-packages/bson/code.py
Normal file
@@ -0,0 +1,99 @@
|
||||
# Copyright 2009-present MongoDB, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Tools for representing JavaScript code in BSON.
|
||||
"""
|
||||
|
||||
from bson.py3compat import abc, string_type, PY3, text_type
|
||||
|
||||
|
||||
class Code(str):
|
||||
"""BSON's JavaScript code type.
|
||||
|
||||
Raises :class:`TypeError` if `code` is not an instance of
|
||||
:class:`basestring` (:class:`str` in python 3) or `scope`
|
||||
is not ``None`` or an instance of :class:`dict`.
|
||||
|
||||
Scope variables can be set by passing a dictionary as the `scope`
|
||||
argument or by using keyword arguments. If a variable is set as a
|
||||
keyword argument it will override any setting for that variable in
|
||||
the `scope` dictionary.
|
||||
|
||||
:Parameters:
|
||||
- `code`: A string containing JavaScript code to be evaluated or another
|
||||
instance of Code. In the latter case, the scope of `code` becomes this
|
||||
Code's :attr:`scope`.
|
||||
- `scope` (optional): dictionary representing the scope in which
|
||||
`code` should be evaluated - a mapping from identifiers (as
|
||||
strings) to values. Defaults to ``None``. This is applied after any
|
||||
scope associated with a given `code` above.
|
||||
- `**kwargs` (optional): scope variables can also be passed as
|
||||
keyword arguments. These are applied after `scope` and `code`.
|
||||
|
||||
.. versionchanged:: 3.4
|
||||
The default value for :attr:`scope` is ``None`` instead of ``{}``.
|
||||
|
||||
"""
|
||||
|
||||
_type_marker = 13
|
||||
|
||||
def __new__(cls, code, scope=None, **kwargs):
|
||||
if not isinstance(code, string_type):
|
||||
raise TypeError("code must be an "
|
||||
"instance of %s" % (string_type.__name__))
|
||||
|
||||
if not PY3 and isinstance(code, text_type):
|
||||
self = str.__new__(cls, code.encode('utf8'))
|
||||
else:
|
||||
self = str.__new__(cls, code)
|
||||
|
||||
try:
|
||||
self.__scope = code.scope
|
||||
except AttributeError:
|
||||
self.__scope = None
|
||||
|
||||
if scope is not None:
|
||||
if not isinstance(scope, abc.Mapping):
|
||||
raise TypeError("scope must be an instance of dict")
|
||||
if self.__scope is not None:
|
||||
self.__scope.update(scope)
|
||||
else:
|
||||
self.__scope = scope
|
||||
|
||||
if kwargs:
|
||||
if self.__scope is not None:
|
||||
self.__scope.update(kwargs)
|
||||
else:
|
||||
self.__scope = kwargs
|
||||
|
||||
return self
|
||||
|
||||
@property
|
||||
def scope(self):
|
||||
"""Scope dictionary for this instance or ``None``.
|
||||
"""
|
||||
return self.__scope
|
||||
|
||||
def __repr__(self):
|
||||
return "Code(%s, %r)" % (str.__repr__(self), self.__scope)
|
||||
|
||||
def __eq__(self, other):
|
||||
if isinstance(other, Code):
|
||||
return (self.__scope, str(self)) == (other.__scope, str(other))
|
||||
return False
|
||||
|
||||
__hash__ = None
|
||||
|
||||
def __ne__(self, other):
|
||||
return not self == other
|
||||
334
venv/lib/python3.8/site-packages/bson/codec_options.py
Normal file
334
venv/lib/python3.8/site-packages/bson/codec_options.py
Normal file
@@ -0,0 +1,334 @@
|
||||
# Copyright 2014-present MongoDB, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Tools for specifying BSON codec options."""
|
||||
|
||||
import datetime
|
||||
|
||||
from abc import abstractmethod
|
||||
from collections import namedtuple
|
||||
|
||||
from bson.py3compat import ABC, abc, abstractproperty, string_type
|
||||
|
||||
from bson.binary import (ALL_UUID_REPRESENTATIONS,
|
||||
PYTHON_LEGACY,
|
||||
UUID_REPRESENTATION_NAMES)
|
||||
|
||||
|
||||
_RAW_BSON_DOCUMENT_MARKER = 101
|
||||
|
||||
|
||||
def _raw_document_class(document_class):
|
||||
"""Determine if a document_class is a RawBSONDocument class."""
|
||||
marker = getattr(document_class, '_type_marker', None)
|
||||
return marker == _RAW_BSON_DOCUMENT_MARKER
|
||||
|
||||
|
||||
class TypeEncoder(ABC):
|
||||
"""Base class for defining type codec classes which describe how a
|
||||
custom type can be transformed to one of the types BSON understands.
|
||||
|
||||
Codec classes must implement the ``python_type`` attribute, and the
|
||||
``transform_python`` method to support encoding.
|
||||
|
||||
See :ref:`custom-type-type-codec` documentation for an example.
|
||||
"""
|
||||
@abstractproperty
|
||||
def python_type(self):
|
||||
"""The Python type to be converted into something serializable."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def transform_python(self, value):
|
||||
"""Convert the given Python object into something serializable."""
|
||||
pass
|
||||
|
||||
|
||||
class TypeDecoder(ABC):
|
||||
"""Base class for defining type codec classes which describe how a
|
||||
BSON type can be transformed to a custom type.
|
||||
|
||||
Codec classes must implement the ``bson_type`` attribute, and the
|
||||
``transform_bson`` method to support decoding.
|
||||
|
||||
See :ref:`custom-type-type-codec` documentation for an example.
|
||||
"""
|
||||
@abstractproperty
|
||||
def bson_type(self):
|
||||
"""The BSON type to be converted into our own type."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def transform_bson(self, value):
|
||||
"""Convert the given BSON value into our own type."""
|
||||
pass
|
||||
|
||||
|
||||
class TypeCodec(TypeEncoder, TypeDecoder):
|
||||
"""Base class for defining type codec classes which describe how a
|
||||
custom type can be transformed to/from one of the types :mod:`bson`
|
||||
can already encode/decode.
|
||||
|
||||
Codec classes must implement the ``python_type`` attribute, and the
|
||||
``transform_python`` method to support encoding, as well as the
|
||||
``bson_type`` attribute, and the ``transform_bson`` method to support
|
||||
decoding.
|
||||
|
||||
See :ref:`custom-type-type-codec` documentation for an example.
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
class TypeRegistry(object):
|
||||
"""Encapsulates type codecs used in encoding and / or decoding BSON, as
|
||||
well as the fallback encoder. Type registries cannot be modified after
|
||||
instantiation.
|
||||
|
||||
``TypeRegistry`` can be initialized with an iterable of type codecs, and
|
||||
a callable for the fallback encoder::
|
||||
|
||||
>>> from bson.codec_options import TypeRegistry
|
||||
>>> type_registry = TypeRegistry([Codec1, Codec2, Codec3, ...],
|
||||
... fallback_encoder)
|
||||
|
||||
See :ref:`custom-type-type-registry` documentation for an example.
|
||||
|
||||
:Parameters:
|
||||
- `type_codecs` (optional): iterable of type codec instances. If
|
||||
``type_codecs`` contains multiple codecs that transform a single
|
||||
python or BSON type, the transformation specified by the type codec
|
||||
occurring last prevails. A TypeError will be raised if one or more
|
||||
type codecs modify the encoding behavior of a built-in :mod:`bson`
|
||||
type.
|
||||
- `fallback_encoder` (optional): callable that accepts a single,
|
||||
unencodable python value and transforms it into a type that
|
||||
:mod:`bson` can encode. See :ref:`fallback-encoder-callable`
|
||||
documentation for an example.
|
||||
"""
|
||||
def __init__(self, type_codecs=None, fallback_encoder=None):
|
||||
self.__type_codecs = list(type_codecs or [])
|
||||
self._fallback_encoder = fallback_encoder
|
||||
self._encoder_map = {}
|
||||
self._decoder_map = {}
|
||||
|
||||
if self._fallback_encoder is not None:
|
||||
if not callable(fallback_encoder):
|
||||
raise TypeError("fallback_encoder %r is not a callable" % (
|
||||
fallback_encoder))
|
||||
|
||||
for codec in self.__type_codecs:
|
||||
is_valid_codec = False
|
||||
if isinstance(codec, TypeEncoder):
|
||||
self._validate_type_encoder(codec)
|
||||
is_valid_codec = True
|
||||
self._encoder_map[codec.python_type] = codec.transform_python
|
||||
if isinstance(codec, TypeDecoder):
|
||||
is_valid_codec = True
|
||||
self._decoder_map[codec.bson_type] = codec.transform_bson
|
||||
if not is_valid_codec:
|
||||
raise TypeError(
|
||||
"Expected an instance of %s, %s, or %s, got %r instead" % (
|
||||
TypeEncoder.__name__, TypeDecoder.__name__,
|
||||
TypeCodec.__name__, codec))
|
||||
|
||||
def _validate_type_encoder(self, codec):
|
||||
from bson import _BUILT_IN_TYPES
|
||||
for pytype in _BUILT_IN_TYPES:
|
||||
if issubclass(codec.python_type, pytype):
|
||||
err_msg = ("TypeEncoders cannot change how built-in types are "
|
||||
"encoded (encoder %s transforms type %s)" %
|
||||
(codec, pytype))
|
||||
raise TypeError(err_msg)
|
||||
|
||||
def __repr__(self):
|
||||
return ('%s(type_codecs=%r, fallback_encoder=%r)' % (
|
||||
self.__class__.__name__, self.__type_codecs,
|
||||
self._fallback_encoder))
|
||||
|
||||
def __eq__(self, other):
|
||||
if not isinstance(other, type(self)):
|
||||
return NotImplemented
|
||||
return ((self._decoder_map == other._decoder_map) and
|
||||
(self._encoder_map == other._encoder_map) and
|
||||
(self._fallback_encoder == other._fallback_encoder))
|
||||
|
||||
|
||||
_options_base = namedtuple(
|
||||
'CodecOptions',
|
||||
('document_class', 'tz_aware', 'uuid_representation',
|
||||
'unicode_decode_error_handler', 'tzinfo', 'type_registry'))
|
||||
|
||||
|
||||
class CodecOptions(_options_base):
|
||||
"""Encapsulates options used encoding and / or decoding BSON.
|
||||
|
||||
The `document_class` option is used to define a custom type for use
|
||||
decoding BSON documents. Access to the underlying raw BSON bytes for
|
||||
a document is available using the :class:`~bson.raw_bson.RawBSONDocument`
|
||||
type::
|
||||
|
||||
>>> from bson.raw_bson import RawBSONDocument
|
||||
>>> from bson.codec_options import CodecOptions
|
||||
>>> codec_options = CodecOptions(document_class=RawBSONDocument)
|
||||
>>> coll = db.get_collection('test', codec_options=codec_options)
|
||||
>>> doc = coll.find_one()
|
||||
>>> doc.raw
|
||||
'\\x16\\x00\\x00\\x00\\x07_id\\x00[0\\x165\\x91\\x10\\xea\\x14\\xe8\\xc5\\x8b\\x93\\x00'
|
||||
|
||||
The document class can be any type that inherits from
|
||||
:class:`~collections.MutableMapping`::
|
||||
|
||||
>>> class AttributeDict(dict):
|
||||
... # A dict that supports attribute access.
|
||||
... def __getattr__(self, key):
|
||||
... return self[key]
|
||||
... def __setattr__(self, key, value):
|
||||
... self[key] = value
|
||||
...
|
||||
>>> codec_options = CodecOptions(document_class=AttributeDict)
|
||||
>>> coll = db.get_collection('test', codec_options=codec_options)
|
||||
>>> doc = coll.find_one()
|
||||
>>> doc._id
|
||||
ObjectId('5b3016359110ea14e8c58b93')
|
||||
|
||||
See :doc:`/examples/datetimes` for examples using the `tz_aware` and
|
||||
`tzinfo` options.
|
||||
|
||||
See :class:`~bson.binary.UUIDLegacy` for examples using the
|
||||
`uuid_representation` option.
|
||||
|
||||
:Parameters:
|
||||
- `document_class`: BSON documents returned in queries will be decoded
|
||||
to an instance of this class. Must be a subclass of
|
||||
:class:`~collections.MutableMapping`. Defaults to :class:`dict`.
|
||||
- `tz_aware`: If ``True``, BSON datetimes will be decoded to timezone
|
||||
aware instances of :class:`~datetime.datetime`. Otherwise they will be
|
||||
naive. Defaults to ``False``.
|
||||
- `uuid_representation`: The BSON representation to use when encoding
|
||||
and decoding instances of :class:`~uuid.UUID`. Defaults to
|
||||
:data:`~bson.binary.PYTHON_LEGACY`.
|
||||
- `unicode_decode_error_handler`: The error handler to apply when
|
||||
a Unicode-related error occurs during BSON decoding that would
|
||||
otherwise raise :exc:`UnicodeDecodeError`. Valid options include
|
||||
'strict', 'replace', and 'ignore'. Defaults to 'strict'.
|
||||
- `tzinfo`: A :class:`~datetime.tzinfo` subclass that specifies the
|
||||
timezone to/from which :class:`~datetime.datetime` objects should be
|
||||
encoded/decoded.
|
||||
- `type_registry`: Instance of :class:`TypeRegistry` used to customize
|
||||
encoding and decoding behavior.
|
||||
|
||||
.. versionadded:: 3.8
|
||||
`type_registry` attribute.
|
||||
|
||||
.. warning:: Care must be taken when changing
|
||||
`unicode_decode_error_handler` from its default value ('strict').
|
||||
The 'replace' and 'ignore' modes should not be used when documents
|
||||
retrieved from the server will be modified in the client application
|
||||
and stored back to the server.
|
||||
"""
|
||||
|
||||
def __new__(cls, document_class=dict,
|
||||
tz_aware=False, uuid_representation=PYTHON_LEGACY,
|
||||
unicode_decode_error_handler="strict",
|
||||
tzinfo=None, type_registry=None):
|
||||
if not (issubclass(document_class, abc.MutableMapping) or
|
||||
_raw_document_class(document_class)):
|
||||
raise TypeError("document_class must be dict, bson.son.SON, "
|
||||
"bson.raw_bson.RawBSONDocument, or a "
|
||||
"sublass of collections.MutableMapping")
|
||||
if not isinstance(tz_aware, bool):
|
||||
raise TypeError("tz_aware must be True or False")
|
||||
if uuid_representation not in ALL_UUID_REPRESENTATIONS:
|
||||
raise ValueError("uuid_representation must be a value "
|
||||
"from bson.binary.ALL_UUID_REPRESENTATIONS")
|
||||
if not isinstance(unicode_decode_error_handler, (string_type, None)):
|
||||
raise ValueError("unicode_decode_error_handler must be a string "
|
||||
"or None")
|
||||
if tzinfo is not None:
|
||||
if not isinstance(tzinfo, datetime.tzinfo):
|
||||
raise TypeError(
|
||||
"tzinfo must be an instance of datetime.tzinfo")
|
||||
if not tz_aware:
|
||||
raise ValueError(
|
||||
"cannot specify tzinfo without also setting tz_aware=True")
|
||||
|
||||
type_registry = type_registry or TypeRegistry()
|
||||
|
||||
if not isinstance(type_registry, TypeRegistry):
|
||||
raise TypeError("type_registry must be an instance of TypeRegistry")
|
||||
|
||||
return tuple.__new__(
|
||||
cls, (document_class, tz_aware, uuid_representation,
|
||||
unicode_decode_error_handler, tzinfo, type_registry))
|
||||
|
||||
def _arguments_repr(self):
|
||||
"""Representation of the arguments used to create this object."""
|
||||
document_class_repr = (
|
||||
'dict' if self.document_class is dict
|
||||
else repr(self.document_class))
|
||||
|
||||
uuid_rep_repr = UUID_REPRESENTATION_NAMES.get(self.uuid_representation,
|
||||
self.uuid_representation)
|
||||
|
||||
return ('document_class=%s, tz_aware=%r, uuid_representation=%s, '
|
||||
'unicode_decode_error_handler=%r, tzinfo=%r, '
|
||||
'type_registry=%r' %
|
||||
(document_class_repr, self.tz_aware, uuid_rep_repr,
|
||||
self.unicode_decode_error_handler, self.tzinfo,
|
||||
self.type_registry))
|
||||
|
||||
def __repr__(self):
|
||||
return '%s(%s)' % (self.__class__.__name__, self._arguments_repr())
|
||||
|
||||
def with_options(self, **kwargs):
|
||||
"""Make a copy of this CodecOptions, overriding some options::
|
||||
|
||||
>>> from bson.codec_options import DEFAULT_CODEC_OPTIONS
|
||||
>>> DEFAULT_CODEC_OPTIONS.tz_aware
|
||||
False
|
||||
>>> options = DEFAULT_CODEC_OPTIONS.with_options(tz_aware=True)
|
||||
>>> options.tz_aware
|
||||
True
|
||||
|
||||
.. versionadded:: 3.5
|
||||
"""
|
||||
return CodecOptions(
|
||||
kwargs.get('document_class', self.document_class),
|
||||
kwargs.get('tz_aware', self.tz_aware),
|
||||
kwargs.get('uuid_representation', self.uuid_representation),
|
||||
kwargs.get('unicode_decode_error_handler',
|
||||
self.unicode_decode_error_handler),
|
||||
kwargs.get('tzinfo', self.tzinfo),
|
||||
kwargs.get('type_registry', self.type_registry)
|
||||
)
|
||||
|
||||
|
||||
DEFAULT_CODEC_OPTIONS = CodecOptions()
|
||||
|
||||
|
||||
def _parse_codec_options(options):
|
||||
"""Parse BSON codec options."""
|
||||
return CodecOptions(
|
||||
document_class=options.get(
|
||||
'document_class', DEFAULT_CODEC_OPTIONS.document_class),
|
||||
tz_aware=options.get(
|
||||
'tz_aware', DEFAULT_CODEC_OPTIONS.tz_aware),
|
||||
uuid_representation=options.get(
|
||||
'uuidrepresentation', DEFAULT_CODEC_OPTIONS.uuid_representation),
|
||||
unicode_decode_error_handler=options.get(
|
||||
'unicode_decode_error_handler',
|
||||
DEFAULT_CODEC_OPTIONS.unicode_decode_error_handler),
|
||||
tzinfo=options.get('tzinfo', DEFAULT_CODEC_OPTIONS.tzinfo),
|
||||
type_registry=options.get(
|
||||
'type_registry', DEFAULT_CODEC_OPTIONS.type_registry))
|
||||
135
venv/lib/python3.8/site-packages/bson/dbref.py
Normal file
135
venv/lib/python3.8/site-packages/bson/dbref.py
Normal file
@@ -0,0 +1,135 @@
|
||||
# Copyright 2009-2015 MongoDB, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Tools for manipulating DBRefs (references to MongoDB documents)."""
|
||||
|
||||
from copy import deepcopy
|
||||
|
||||
from bson.py3compat import iteritems, string_type
|
||||
from bson.son import SON
|
||||
|
||||
|
||||
class DBRef(object):
|
||||
"""A reference to a document stored in MongoDB.
|
||||
"""
|
||||
|
||||
# DBRef isn't actually a BSON "type" so this number was arbitrarily chosen.
|
||||
_type_marker = 100
|
||||
|
||||
def __init__(self, collection, id, database=None, _extra={}, **kwargs):
|
||||
"""Initialize a new :class:`DBRef`.
|
||||
|
||||
Raises :class:`TypeError` if `collection` or `database` is not
|
||||
an instance of :class:`basestring` (:class:`str` in python 3).
|
||||
`database` is optional and allows references to documents to work
|
||||
across databases. Any additional keyword arguments will create
|
||||
additional fields in the resultant embedded document.
|
||||
|
||||
:Parameters:
|
||||
- `collection`: name of the collection the document is stored in
|
||||
- `id`: the value of the document's ``"_id"`` field
|
||||
- `database` (optional): name of the database to reference
|
||||
- `**kwargs` (optional): additional keyword arguments will
|
||||
create additional, custom fields
|
||||
|
||||
.. mongodoc:: dbrefs
|
||||
"""
|
||||
if not isinstance(collection, string_type):
|
||||
raise TypeError("collection must be an "
|
||||
"instance of %s" % string_type.__name__)
|
||||
if database is not None and not isinstance(database, string_type):
|
||||
raise TypeError("database must be an "
|
||||
"instance of %s" % string_type.__name__)
|
||||
|
||||
self.__collection = collection
|
||||
self.__id = id
|
||||
self.__database = database
|
||||
kwargs.update(_extra)
|
||||
self.__kwargs = kwargs
|
||||
|
||||
@property
|
||||
def collection(self):
|
||||
"""Get the name of this DBRef's collection as unicode.
|
||||
"""
|
||||
return self.__collection
|
||||
|
||||
@property
|
||||
def id(self):
|
||||
"""Get this DBRef's _id.
|
||||
"""
|
||||
return self.__id
|
||||
|
||||
@property
|
||||
def database(self):
|
||||
"""Get the name of this DBRef's database.
|
||||
|
||||
Returns None if this DBRef doesn't specify a database.
|
||||
"""
|
||||
return self.__database
|
||||
|
||||
def __getattr__(self, key):
|
||||
try:
|
||||
return self.__kwargs[key]
|
||||
except KeyError:
|
||||
raise AttributeError(key)
|
||||
|
||||
# Have to provide __setstate__ to avoid
|
||||
# infinite recursion since we override
|
||||
# __getattr__.
|
||||
def __setstate__(self, state):
|
||||
self.__dict__.update(state)
|
||||
|
||||
def as_doc(self):
|
||||
"""Get the SON document representation of this DBRef.
|
||||
|
||||
Generally not needed by application developers
|
||||
"""
|
||||
doc = SON([("$ref", self.collection),
|
||||
("$id", self.id)])
|
||||
if self.database is not None:
|
||||
doc["$db"] = self.database
|
||||
doc.update(self.__kwargs)
|
||||
return doc
|
||||
|
||||
def __repr__(self):
|
||||
extra = "".join([", %s=%r" % (k, v)
|
||||
for k, v in iteritems(self.__kwargs)])
|
||||
if self.database is None:
|
||||
return "DBRef(%r, %r%s)" % (self.collection, self.id, extra)
|
||||
return "DBRef(%r, %r, %r%s)" % (self.collection, self.id,
|
||||
self.database, extra)
|
||||
|
||||
def __eq__(self, other):
|
||||
if isinstance(other, DBRef):
|
||||
us = (self.__database, self.__collection,
|
||||
self.__id, self.__kwargs)
|
||||
them = (other.__database, other.__collection,
|
||||
other.__id, other.__kwargs)
|
||||
return us == them
|
||||
return NotImplemented
|
||||
|
||||
def __ne__(self, other):
|
||||
return not self == other
|
||||
|
||||
def __hash__(self):
|
||||
"""Get a hash value for this :class:`DBRef`."""
|
||||
return hash((self.__collection, self.__id, self.__database,
|
||||
tuple(sorted(self.__kwargs.items()))))
|
||||
|
||||
def __deepcopy__(self, memo):
|
||||
"""Support function for `copy.deepcopy()`."""
|
||||
return DBRef(deepcopy(self.__collection, memo),
|
||||
deepcopy(self.__id, memo),
|
||||
deepcopy(self.__database, memo),
|
||||
deepcopy(self.__kwargs, memo))
|
||||
335
venv/lib/python3.8/site-packages/bson/decimal128.py
Normal file
335
venv/lib/python3.8/site-packages/bson/decimal128.py
Normal file
@@ -0,0 +1,335 @@
|
||||
# Copyright 2016-present MongoDB, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Tools for working with the BSON decimal128 type.
|
||||
|
||||
.. versionadded:: 3.4
|
||||
|
||||
.. note:: The Decimal128 BSON type requires MongoDB 3.4+.
|
||||
"""
|
||||
|
||||
import decimal
|
||||
import struct
|
||||
import sys
|
||||
|
||||
from bson.py3compat import (PY3 as _PY3,
|
||||
string_type as _string_type)
|
||||
|
||||
|
||||
if _PY3:
|
||||
_from_bytes = int.from_bytes # pylint: disable=no-member, invalid-name
|
||||
else:
|
||||
import binascii
|
||||
def _from_bytes(value, dummy, _int=int, _hexlify=binascii.hexlify):
|
||||
"An implementation of int.from_bytes for python 2.x."
|
||||
return _int(_hexlify(value), 16)
|
||||
|
||||
|
||||
_PACK_64 = struct.Struct("<Q").pack
|
||||
_UNPACK_64 = struct.Struct("<Q").unpack
|
||||
|
||||
_EXPONENT_MASK = 3 << 61
|
||||
_EXPONENT_BIAS = 6176
|
||||
_EXPONENT_MAX = 6144
|
||||
_EXPONENT_MIN = -6143
|
||||
_MAX_DIGITS = 34
|
||||
|
||||
_INF = 0x7800000000000000
|
||||
_NAN = 0x7c00000000000000
|
||||
_SNAN = 0x7e00000000000000
|
||||
_SIGN = 0x8000000000000000
|
||||
|
||||
_NINF = (_INF + _SIGN, 0)
|
||||
_PINF = (_INF, 0)
|
||||
_NNAN = (_NAN + _SIGN, 0)
|
||||
_PNAN = (_NAN, 0)
|
||||
_NSNAN = (_SNAN + _SIGN, 0)
|
||||
_PSNAN = (_SNAN, 0)
|
||||
|
||||
_CTX_OPTIONS = {
|
||||
'prec': _MAX_DIGITS,
|
||||
'rounding': decimal.ROUND_HALF_EVEN,
|
||||
'Emin': _EXPONENT_MIN,
|
||||
'Emax': _EXPONENT_MAX,
|
||||
'capitals': 1,
|
||||
'flags': [],
|
||||
'traps': [decimal.InvalidOperation,
|
||||
decimal.Overflow,
|
||||
decimal.Inexact]
|
||||
}
|
||||
|
||||
try:
|
||||
# Python >= 3.3, cdecimal
|
||||
decimal.Context(clamp=1) # pylint: disable=unexpected-keyword-arg
|
||||
_CTX_OPTIONS['clamp'] = 1
|
||||
except TypeError:
|
||||
# Python < 3.3
|
||||
_CTX_OPTIONS['_clamp'] = 1
|
||||
|
||||
_DEC128_CTX = decimal.Context(**_CTX_OPTIONS.copy())
|
||||
|
||||
|
||||
def create_decimal128_context():
|
||||
"""Returns an instance of :class:`decimal.Context` appropriate
|
||||
for working with IEEE-754 128-bit decimal floating point values.
|
||||
"""
|
||||
opts = _CTX_OPTIONS.copy()
|
||||
opts['traps'] = []
|
||||
return decimal.Context(**opts)
|
||||
|
||||
|
||||
def _decimal_to_128(value):
|
||||
"""Converts a decimal.Decimal to BID (high bits, low bits).
|
||||
|
||||
:Parameters:
|
||||
- `value`: An instance of decimal.Decimal
|
||||
"""
|
||||
with decimal.localcontext(_DEC128_CTX) as ctx:
|
||||
value = ctx.create_decimal(value)
|
||||
|
||||
if value.is_infinite():
|
||||
return _NINF if value.is_signed() else _PINF
|
||||
|
||||
sign, digits, exponent = value.as_tuple()
|
||||
|
||||
if value.is_nan():
|
||||
if digits:
|
||||
raise ValueError("NaN with debug payload is not supported")
|
||||
if value.is_snan():
|
||||
return _NSNAN if value.is_signed() else _PSNAN
|
||||
return _NNAN if value.is_signed() else _PNAN
|
||||
|
||||
significand = int("".join([str(digit) for digit in digits]))
|
||||
bit_length = significand.bit_length()
|
||||
|
||||
high = 0
|
||||
low = 0
|
||||
for i in range(min(64, bit_length)):
|
||||
if significand & (1 << i):
|
||||
low |= 1 << i
|
||||
|
||||
for i in range(64, bit_length):
|
||||
if significand & (1 << i):
|
||||
high |= 1 << (i - 64)
|
||||
|
||||
biased_exponent = exponent + _EXPONENT_BIAS
|
||||
|
||||
if high >> 49 == 1:
|
||||
high = high & 0x7fffffffffff
|
||||
high |= _EXPONENT_MASK
|
||||
high |= (biased_exponent & 0x3fff) << 47
|
||||
else:
|
||||
high |= biased_exponent << 49
|
||||
|
||||
if sign:
|
||||
high |= _SIGN
|
||||
|
||||
return high, low
|
||||
|
||||
|
||||
class Decimal128(object):
|
||||
"""BSON Decimal128 type::
|
||||
|
||||
>>> Decimal128(Decimal("0.0005"))
|
||||
Decimal128('0.0005')
|
||||
>>> Decimal128("0.0005")
|
||||
Decimal128('0.0005')
|
||||
>>> Decimal128((3474527112516337664, 5))
|
||||
Decimal128('0.0005')
|
||||
|
||||
:Parameters:
|
||||
- `value`: An instance of :class:`decimal.Decimal`, string, or tuple of
|
||||
(high bits, low bits) from Binary Integer Decimal (BID) format.
|
||||
|
||||
.. note:: :class:`~Decimal128` uses an instance of :class:`decimal.Context`
|
||||
configured for IEEE-754 Decimal128 when validating parameters.
|
||||
Signals like :class:`decimal.InvalidOperation`, :class:`decimal.Inexact`,
|
||||
and :class:`decimal.Overflow` are trapped and raised as exceptions::
|
||||
|
||||
>>> Decimal128(".13.1")
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
...
|
||||
decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]
|
||||
>>>
|
||||
>>> Decimal128("1E-6177")
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
...
|
||||
decimal.Inexact: [<class 'decimal.Inexact'>]
|
||||
>>>
|
||||
>>> Decimal128("1E6145")
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
...
|
||||
decimal.Overflow: [<class 'decimal.Overflow'>, <class 'decimal.Rounded'>]
|
||||
|
||||
To ensure the result of a calculation can always be stored as BSON
|
||||
Decimal128 use the context returned by
|
||||
:func:`create_decimal128_context`::
|
||||
|
||||
>>> import decimal
|
||||
>>> decimal128_ctx = create_decimal128_context()
|
||||
>>> with decimal.localcontext(decimal128_ctx) as ctx:
|
||||
... Decimal128(ctx.create_decimal(".13.3"))
|
||||
...
|
||||
Decimal128('NaN')
|
||||
>>>
|
||||
>>> with decimal.localcontext(decimal128_ctx) as ctx:
|
||||
... Decimal128(ctx.create_decimal("1E-6177"))
|
||||
...
|
||||
Decimal128('0E-6176')
|
||||
>>>
|
||||
>>> with decimal.localcontext(DECIMAL128_CTX) as ctx:
|
||||
... Decimal128(ctx.create_decimal("1E6145"))
|
||||
...
|
||||
Decimal128('Infinity')
|
||||
|
||||
To match the behavior of MongoDB's Decimal128 implementation
|
||||
str(Decimal(value)) may not match str(Decimal128(value)) for NaN values::
|
||||
|
||||
>>> Decimal128(Decimal('NaN'))
|
||||
Decimal128('NaN')
|
||||
>>> Decimal128(Decimal('-NaN'))
|
||||
Decimal128('NaN')
|
||||
>>> Decimal128(Decimal('sNaN'))
|
||||
Decimal128('NaN')
|
||||
>>> Decimal128(Decimal('-sNaN'))
|
||||
Decimal128('NaN')
|
||||
|
||||
However, :meth:`~Decimal128.to_decimal` will return the exact value::
|
||||
|
||||
>>> Decimal128(Decimal('NaN')).to_decimal()
|
||||
Decimal('NaN')
|
||||
>>> Decimal128(Decimal('-NaN')).to_decimal()
|
||||
Decimal('-NaN')
|
||||
>>> Decimal128(Decimal('sNaN')).to_decimal()
|
||||
Decimal('sNaN')
|
||||
>>> Decimal128(Decimal('-sNaN')).to_decimal()
|
||||
Decimal('-sNaN')
|
||||
|
||||
Two instances of :class:`Decimal128` compare equal if their Binary
|
||||
Integer Decimal encodings are equal::
|
||||
|
||||
>>> Decimal128('NaN') == Decimal128('NaN')
|
||||
True
|
||||
>>> Decimal128('NaN').bid == Decimal128('NaN').bid
|
||||
True
|
||||
|
||||
This differs from :class:`decimal.Decimal` comparisons for NaN::
|
||||
|
||||
>>> Decimal('NaN') == Decimal('NaN')
|
||||
False
|
||||
"""
|
||||
__slots__ = ('__high', '__low')
|
||||
|
||||
_type_marker = 19
|
||||
|
||||
def __init__(self, value):
|
||||
if isinstance(value, (_string_type, decimal.Decimal)):
|
||||
self.__high, self.__low = _decimal_to_128(value)
|
||||
elif isinstance(value, (list, tuple)):
|
||||
if len(value) != 2:
|
||||
raise ValueError('Invalid size for creation of Decimal128 '
|
||||
'from list or tuple. Must have exactly 2 '
|
||||
'elements.')
|
||||
self.__high, self.__low = value
|
||||
else:
|
||||
raise TypeError("Cannot convert %r to Decimal128" % (value,))
|
||||
|
||||
def to_decimal(self):
|
||||
"""Returns an instance of :class:`decimal.Decimal` for this
|
||||
:class:`Decimal128`.
|
||||
"""
|
||||
high = self.__high
|
||||
low = self.__low
|
||||
sign = 1 if (high & _SIGN) else 0
|
||||
|
||||
if (high & _SNAN) == _SNAN:
|
||||
return decimal.Decimal((sign, (), 'N'))
|
||||
elif (high & _NAN) == _NAN:
|
||||
return decimal.Decimal((sign, (), 'n'))
|
||||
elif (high & _INF) == _INF:
|
||||
return decimal.Decimal((sign, (), 'F'))
|
||||
|
||||
if (high & _EXPONENT_MASK) == _EXPONENT_MASK:
|
||||
exponent = ((high & 0x1fffe00000000000) >> 47) - _EXPONENT_BIAS
|
||||
return decimal.Decimal((sign, (0,), exponent))
|
||||
else:
|
||||
exponent = ((high & 0x7fff800000000000) >> 49) - _EXPONENT_BIAS
|
||||
|
||||
arr = bytearray(15)
|
||||
mask = 0x00000000000000ff
|
||||
for i in range(14, 6, -1):
|
||||
arr[i] = (low & mask) >> ((14 - i) << 3)
|
||||
mask = mask << 8
|
||||
|
||||
mask = 0x00000000000000ff
|
||||
for i in range(6, 0, -1):
|
||||
arr[i] = (high & mask) >> ((6 - i) << 3)
|
||||
mask = mask << 8
|
||||
|
||||
mask = 0x0001000000000000
|
||||
arr[0] = (high & mask) >> 48
|
||||
|
||||
# cdecimal only accepts a tuple for digits.
|
||||
digits = tuple(
|
||||
int(digit) for digit in str(_from_bytes(arr, 'big')))
|
||||
|
||||
with decimal.localcontext(_DEC128_CTX) as ctx:
|
||||
return ctx.create_decimal((sign, digits, exponent))
|
||||
|
||||
@classmethod
|
||||
def from_bid(cls, value):
|
||||
"""Create an instance of :class:`Decimal128` from Binary Integer
|
||||
Decimal string.
|
||||
|
||||
:Parameters:
|
||||
- `value`: 16 byte string (128-bit IEEE 754-2008 decimal floating
|
||||
point in Binary Integer Decimal (BID) format).
|
||||
"""
|
||||
if not isinstance(value, bytes):
|
||||
raise TypeError("value must be an instance of bytes")
|
||||
if len(value) != 16:
|
||||
raise ValueError("value must be exactly 16 bytes")
|
||||
return cls((_UNPACK_64(value[8:])[0], _UNPACK_64(value[:8])[0]))
|
||||
|
||||
@property
|
||||
def bid(self):
|
||||
"""The Binary Integer Decimal (BID) encoding of this instance."""
|
||||
return _PACK_64(self.__low) + _PACK_64(self.__high)
|
||||
|
||||
def __str__(self):
|
||||
dec = self.to_decimal()
|
||||
if dec.is_nan():
|
||||
# Required by the drivers spec to match MongoDB behavior.
|
||||
return "NaN"
|
||||
return str(dec)
|
||||
|
||||
def __repr__(self):
|
||||
return "Decimal128('%s')" % (str(self),)
|
||||
|
||||
def __setstate__(self, value):
|
||||
self.__high, self.__low = value
|
||||
|
||||
def __getstate__(self):
|
||||
return self.__high, self.__low
|
||||
|
||||
def __eq__(self, other):
|
||||
if isinstance(other, Decimal128):
|
||||
return self.bid == other.bid
|
||||
return NotImplemented
|
||||
|
||||
def __ne__(self, other):
|
||||
return not self == other
|
||||
40
venv/lib/python3.8/site-packages/bson/errors.py
Normal file
40
venv/lib/python3.8/site-packages/bson/errors.py
Normal file
@@ -0,0 +1,40 @@
|
||||
# Copyright 2009-present MongoDB, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Exceptions raised by the BSON package."""
|
||||
|
||||
|
||||
class BSONError(Exception):
|
||||
"""Base class for all BSON exceptions.
|
||||
"""
|
||||
|
||||
|
||||
class InvalidBSON(BSONError):
|
||||
"""Raised when trying to create a BSON object from invalid data.
|
||||
"""
|
||||
|
||||
|
||||
class InvalidStringData(BSONError):
|
||||
"""Raised when trying to encode a string containing non-UTF8 data.
|
||||
"""
|
||||
|
||||
|
||||
class InvalidDocument(BSONError):
|
||||
"""Raised when trying to create a BSON object from an invalid document.
|
||||
"""
|
||||
|
||||
|
||||
class InvalidId(BSONError):
|
||||
"""Raised when trying to create an ObjectId from invalid data.
|
||||
"""
|
||||
34
venv/lib/python3.8/site-packages/bson/int64.py
Normal file
34
venv/lib/python3.8/site-packages/bson/int64.py
Normal file
@@ -0,0 +1,34 @@
|
||||
# Copyright 2014-2015 MongoDB, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""A BSON wrapper for long (int in python3)"""
|
||||
|
||||
from bson.py3compat import PY3
|
||||
|
||||
if PY3:
|
||||
long = int
|
||||
|
||||
|
||||
class Int64(long):
|
||||
"""Representation of the BSON int64 type.
|
||||
|
||||
This is necessary because every integral number is an :class:`int` in
|
||||
Python 3. Small integral numbers are encoded to BSON int32 by default,
|
||||
but Int64 numbers will always be encoded to BSON int64.
|
||||
|
||||
:Parameters:
|
||||
- `value`: the numeric value to represent
|
||||
"""
|
||||
|
||||
_type_marker = 18
|
||||
829
venv/lib/python3.8/site-packages/bson/json_util.py
Normal file
829
venv/lib/python3.8/site-packages/bson/json_util.py
Normal file
@@ -0,0 +1,829 @@
|
||||
# Copyright 2009-present MongoDB, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Tools for using Python's :mod:`json` module with BSON documents.
|
||||
|
||||
This module provides two helper methods `dumps` and `loads` that wrap the
|
||||
native :mod:`json` methods and provide explicit BSON conversion to and from
|
||||
JSON. :class:`~bson.json_util.JSONOptions` provides a way to control how JSON
|
||||
is emitted and parsed, with the default being the legacy PyMongo format.
|
||||
:mod:`~bson.json_util` can also generate Canonical or Relaxed `Extended JSON`_
|
||||
when :const:`CANONICAL_JSON_OPTIONS` or :const:`RELAXED_JSON_OPTIONS` is
|
||||
provided, respectively.
|
||||
|
||||
.. _Extended JSON: https://github.com/mongodb/specifications/blob/master/source/extended-json.rst
|
||||
|
||||
Example usage (deserialization):
|
||||
|
||||
.. doctest::
|
||||
|
||||
>>> from bson.json_util import loads
|
||||
>>> loads('[{"foo": [1, 2]}, {"bar": {"hello": "world"}}, {"code": {"$scope": {}, "$code": "function x() { return 1; }"}}, {"bin": {"$type": "80", "$binary": "AQIDBA=="}}]')
|
||||
[{u'foo': [1, 2]}, {u'bar': {u'hello': u'world'}}, {u'code': Code('function x() { return 1; }', {})}, {u'bin': Binary('...', 128)}]
|
||||
|
||||
Example usage (serialization):
|
||||
|
||||
.. doctest::
|
||||
|
||||
>>> from bson import Binary, Code
|
||||
>>> from bson.json_util import dumps
|
||||
>>> dumps([{'foo': [1, 2]},
|
||||
... {'bar': {'hello': 'world'}},
|
||||
... {'code': Code("function x() { return 1; }", {})},
|
||||
... {'bin': Binary(b"\x01\x02\x03\x04")}])
|
||||
'[{"foo": [1, 2]}, {"bar": {"hello": "world"}}, {"code": {"$code": "function x() { return 1; }", "$scope": {}}}, {"bin": {"$binary": "AQIDBA==", "$type": "00"}}]'
|
||||
|
||||
Example usage (with :const:`CANONICAL_JSON_OPTIONS`):
|
||||
|
||||
.. doctest::
|
||||
|
||||
>>> from bson import Binary, Code
|
||||
>>> from bson.json_util import dumps, CANONICAL_JSON_OPTIONS
|
||||
>>> dumps([{'foo': [1, 2]},
|
||||
... {'bar': {'hello': 'world'}},
|
||||
... {'code': Code("function x() { return 1; }")},
|
||||
... {'bin': Binary(b"\x01\x02\x03\x04")}],
|
||||
... json_options=CANONICAL_JSON_OPTIONS)
|
||||
'[{"foo": [{"$numberInt": "1"}, {"$numberInt": "2"}]}, {"bar": {"hello": "world"}}, {"code": {"$code": "function x() { return 1; }"}}, {"bin": {"$binary": {"base64": "AQIDBA==", "subType": "00"}}}]'
|
||||
|
||||
Example usage (with :const:`RELAXED_JSON_OPTIONS`):
|
||||
|
||||
.. doctest::
|
||||
|
||||
>>> from bson import Binary, Code
|
||||
>>> from bson.json_util import dumps, RELAXED_JSON_OPTIONS
|
||||
>>> dumps([{'foo': [1, 2]},
|
||||
... {'bar': {'hello': 'world'}},
|
||||
... {'code': Code("function x() { return 1; }")},
|
||||
... {'bin': Binary(b"\x01\x02\x03\x04")}],
|
||||
... json_options=RELAXED_JSON_OPTIONS)
|
||||
'[{"foo": [1, 2]}, {"bar": {"hello": "world"}}, {"code": {"$code": "function x() { return 1; }"}}, {"bin": {"$binary": {"base64": "AQIDBA==", "subType": "00"}}}]'
|
||||
|
||||
Alternatively, you can manually pass the `default` to :func:`json.dumps`.
|
||||
It won't handle :class:`~bson.binary.Binary` and :class:`~bson.code.Code`
|
||||
instances (as they are extended strings you can't provide custom defaults),
|
||||
but it will be faster as there is less recursion.
|
||||
|
||||
.. note::
|
||||
If your application does not need the flexibility offered by
|
||||
:class:`JSONOptions` and spends a large amount of time in the `json_util`
|
||||
module, look to
|
||||
`python-bsonjs <https://pypi.python.org/pypi/python-bsonjs>`_ for a nice
|
||||
performance improvement. `python-bsonjs` is a fast BSON to MongoDB
|
||||
Extended JSON converter for Python built on top of
|
||||
`libbson <https://github.com/mongodb/libbson>`_. `python-bsonjs` works best
|
||||
with PyMongo when using :class:`~bson.raw_bson.RawBSONDocument`.
|
||||
|
||||
.. versionchanged:: 2.8
|
||||
The output format for :class:`~bson.timestamp.Timestamp` has changed from
|
||||
'{"t": <int>, "i": <int>}' to '{"$timestamp": {"t": <int>, "i": <int>}}'.
|
||||
This new format will be decoded to an instance of
|
||||
:class:`~bson.timestamp.Timestamp`. The old format will continue to be
|
||||
decoded to a python dict as before. Encoding to the old format is no longer
|
||||
supported as it was never correct and loses type information.
|
||||
Added support for $numberLong and $undefined - new in MongoDB 2.6 - and
|
||||
parsing $date in ISO-8601 format.
|
||||
|
||||
.. versionchanged:: 2.7
|
||||
Preserves order when rendering SON, Timestamp, Code, Binary, and DBRef
|
||||
instances.
|
||||
|
||||
.. versionchanged:: 2.3
|
||||
Added dumps and loads helpers to automatically handle conversion to and
|
||||
from json and supports :class:`~bson.binary.Binary` and
|
||||
:class:`~bson.code.Code`
|
||||
"""
|
||||
|
||||
import base64
|
||||
import datetime
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
from pymongo.errors import ConfigurationError
|
||||
|
||||
import bson
|
||||
from bson import EPOCH_AWARE, EPOCH_NAIVE, RE_TYPE, SON
|
||||
from bson.binary import (Binary, JAVA_LEGACY, CSHARP_LEGACY, OLD_UUID_SUBTYPE,
|
||||
UUID_SUBTYPE)
|
||||
from bson.code import Code
|
||||
from bson.codec_options import CodecOptions
|
||||
from bson.dbref import DBRef
|
||||
from bson.decimal128 import Decimal128
|
||||
from bson.int64 import Int64
|
||||
from bson.max_key import MaxKey
|
||||
from bson.min_key import MinKey
|
||||
from bson.objectid import ObjectId
|
||||
from bson.py3compat import (PY3, iteritems, integer_types, string_type,
|
||||
text_type)
|
||||
from bson.regex import Regex
|
||||
from bson.timestamp import Timestamp
|
||||
from bson.tz_util import utc
|
||||
|
||||
|
||||
_RE_OPT_TABLE = {
|
||||
"i": re.I,
|
||||
"l": re.L,
|
||||
"m": re.M,
|
||||
"s": re.S,
|
||||
"u": re.U,
|
||||
"x": re.X,
|
||||
}
|
||||
|
||||
# Dollar-prefixed keys which may appear in DBRefs.
|
||||
_DBREF_KEYS = frozenset(['$id', '$ref', '$db'])
|
||||
|
||||
|
||||
class DatetimeRepresentation:
|
||||
LEGACY = 0
|
||||
"""Legacy MongoDB Extended JSON datetime representation.
|
||||
|
||||
:class:`datetime.datetime` instances will be encoded to JSON in the
|
||||
format `{"$date": <dateAsMilliseconds>}`, where `dateAsMilliseconds` is
|
||||
a 64-bit signed integer giving the number of milliseconds since the Unix
|
||||
epoch UTC. This was the default encoding before PyMongo version 3.4.
|
||||
|
||||
.. versionadded:: 3.4
|
||||
"""
|
||||
|
||||
NUMBERLONG = 1
|
||||
"""NumberLong datetime representation.
|
||||
|
||||
:class:`datetime.datetime` instances will be encoded to JSON in the
|
||||
format `{"$date": {"$numberLong": "<dateAsMilliseconds>"}}`,
|
||||
where `dateAsMilliseconds` is the string representation of a 64-bit signed
|
||||
integer giving the number of milliseconds since the Unix epoch UTC.
|
||||
|
||||
.. versionadded:: 3.4
|
||||
"""
|
||||
|
||||
ISO8601 = 2
|
||||
"""ISO-8601 datetime representation.
|
||||
|
||||
:class:`datetime.datetime` instances greater than or equal to the Unix
|
||||
epoch UTC will be encoded to JSON in the format `{"$date": "<ISO-8601>"}`.
|
||||
:class:`datetime.datetime` instances before the Unix epoch UTC will be
|
||||
encoded as if the datetime representation is
|
||||
:const:`~DatetimeRepresentation.NUMBERLONG`.
|
||||
|
||||
.. versionadded:: 3.4
|
||||
"""
|
||||
|
||||
|
||||
class JSONMode:
|
||||
LEGACY = 0
|
||||
"""Legacy Extended JSON representation.
|
||||
|
||||
In this mode, :func:`~bson.json_util.dumps` produces PyMongo's legacy
|
||||
non-standard JSON output. Consider using
|
||||
:const:`~bson.json_util.JSONMode.RELAXED` or
|
||||
:const:`~bson.json_util.JSONMode.CANONICAL` instead.
|
||||
|
||||
.. versionadded:: 3.5
|
||||
"""
|
||||
|
||||
RELAXED = 1
|
||||
"""Relaxed Extended JSON representation.
|
||||
|
||||
In this mode, :func:`~bson.json_util.dumps` produces Relaxed Extended JSON,
|
||||
a mostly JSON-like format. Consider using this for things like a web API,
|
||||
where one is sending a document (or a projection of a document) that only
|
||||
uses ordinary JSON type primitives. In particular, the ``int``,
|
||||
:class:`~bson.int64.Int64`, and ``float`` numeric types are represented in
|
||||
the native JSON number format. This output is also the most human readable
|
||||
and is useful for debugging and documentation.
|
||||
|
||||
.. seealso:: The specification for Relaxed `Extended JSON`_.
|
||||
|
||||
.. versionadded:: 3.5
|
||||
"""
|
||||
|
||||
CANONICAL = 2
|
||||
"""Canonical Extended JSON representation.
|
||||
|
||||
In this mode, :func:`~bson.json_util.dumps` produces Canonical Extended
|
||||
JSON, a type preserving format. Consider using this for things like
|
||||
testing, where one has to precisely specify expected types in JSON. In
|
||||
particular, the ``int``, :class:`~bson.int64.Int64`, and ``float`` numeric
|
||||
types are encoded with type wrappers.
|
||||
|
||||
.. seealso:: The specification for Canonical `Extended JSON`_.
|
||||
|
||||
.. versionadded:: 3.5
|
||||
"""
|
||||
|
||||
|
||||
class JSONOptions(CodecOptions):
|
||||
"""Encapsulates JSON options for :func:`dumps` and :func:`loads`.
|
||||
|
||||
:Parameters:
|
||||
- `strict_number_long`: If ``True``, :class:`~bson.int64.Int64` objects
|
||||
are encoded to MongoDB Extended JSON's *Strict mode* type
|
||||
`NumberLong`, ie ``'{"$numberLong": "<number>" }'``. Otherwise they
|
||||
will be encoded as an `int`. Defaults to ``False``.
|
||||
- `datetime_representation`: The representation to use when encoding
|
||||
instances of :class:`datetime.datetime`. Defaults to
|
||||
:const:`~DatetimeRepresentation.LEGACY`.
|
||||
- `strict_uuid`: If ``True``, :class:`uuid.UUID` object are encoded to
|
||||
MongoDB Extended JSON's *Strict mode* type `Binary`. Otherwise it
|
||||
will be encoded as ``'{"$uuid": "<hex>" }'``. Defaults to ``False``.
|
||||
- `json_mode`: The :class:`JSONMode` to use when encoding BSON types to
|
||||
Extended JSON. Defaults to :const:`~JSONMode.LEGACY`.
|
||||
- `document_class`: BSON documents returned by :func:`loads` will be
|
||||
decoded to an instance of this class. Must be a subclass of
|
||||
:class:`collections.MutableMapping`. Defaults to :class:`dict`.
|
||||
- `uuid_representation`: The BSON representation to use when encoding
|
||||
and decoding instances of :class:`uuid.UUID`. Defaults to
|
||||
:const:`~bson.binary.PYTHON_LEGACY`.
|
||||
- `tz_aware`: If ``True``, MongoDB Extended JSON's *Strict mode* type
|
||||
`Date` will be decoded to timezone aware instances of
|
||||
:class:`datetime.datetime`. Otherwise they will be naive. Defaults
|
||||
to ``True``.
|
||||
- `tzinfo`: A :class:`datetime.tzinfo` subclass that specifies the
|
||||
timezone from which :class:`~datetime.datetime` objects should be
|
||||
decoded. Defaults to :const:`~bson.tz_util.utc`.
|
||||
- `args`: arguments to :class:`~bson.codec_options.CodecOptions`
|
||||
- `kwargs`: arguments to :class:`~bson.codec_options.CodecOptions`
|
||||
|
||||
.. seealso:: The specification for Relaxed and Canonical `Extended JSON`_.
|
||||
|
||||
.. versionadded:: 3.4
|
||||
|
||||
.. versionchanged:: 3.5
|
||||
Accepts the optional parameter `json_mode`.
|
||||
|
||||
"""
|
||||
|
||||
def __new__(cls, strict_number_long=False,
|
||||
datetime_representation=DatetimeRepresentation.LEGACY,
|
||||
strict_uuid=False, json_mode=JSONMode.LEGACY,
|
||||
*args, **kwargs):
|
||||
kwargs["tz_aware"] = kwargs.get("tz_aware", True)
|
||||
if kwargs["tz_aware"]:
|
||||
kwargs["tzinfo"] = kwargs.get("tzinfo", utc)
|
||||
if datetime_representation not in (DatetimeRepresentation.LEGACY,
|
||||
DatetimeRepresentation.NUMBERLONG,
|
||||
DatetimeRepresentation.ISO8601):
|
||||
raise ConfigurationError(
|
||||
"JSONOptions.datetime_representation must be one of LEGACY, "
|
||||
"NUMBERLONG, or ISO8601 from DatetimeRepresentation.")
|
||||
self = super(JSONOptions, cls).__new__(cls, *args, **kwargs)
|
||||
if json_mode not in (JSONMode.LEGACY,
|
||||
JSONMode.RELAXED,
|
||||
JSONMode.CANONICAL):
|
||||
raise ConfigurationError(
|
||||
"JSONOptions.json_mode must be one of LEGACY, RELAXED, "
|
||||
"or CANONICAL from JSONMode.")
|
||||
self.json_mode = json_mode
|
||||
if self.json_mode == JSONMode.RELAXED:
|
||||
self.strict_number_long = False
|
||||
self.datetime_representation = DatetimeRepresentation.ISO8601
|
||||
self.strict_uuid = True
|
||||
elif self.json_mode == JSONMode.CANONICAL:
|
||||
self.strict_number_long = True
|
||||
self.datetime_representation = DatetimeRepresentation.NUMBERLONG
|
||||
self.strict_uuid = True
|
||||
else:
|
||||
self.strict_number_long = strict_number_long
|
||||
self.datetime_representation = datetime_representation
|
||||
self.strict_uuid = strict_uuid
|
||||
return self
|
||||
|
||||
def _arguments_repr(self):
|
||||
return ('strict_number_long=%r, '
|
||||
'datetime_representation=%r, '
|
||||
'strict_uuid=%r, json_mode=%r, %s' % (
|
||||
self.strict_number_long,
|
||||
self.datetime_representation,
|
||||
self.strict_uuid,
|
||||
self.json_mode,
|
||||
super(JSONOptions, self)._arguments_repr()))
|
||||
|
||||
|
||||
LEGACY_JSON_OPTIONS = JSONOptions(json_mode=JSONMode.LEGACY)
|
||||
""":class:`JSONOptions` for encoding to PyMongo's legacy JSON format.
|
||||
|
||||
.. seealso:: The documentation for :const:`bson.json_util.JSONMode.LEGACY`.
|
||||
|
||||
.. versionadded:: 3.5
|
||||
"""
|
||||
|
||||
DEFAULT_JSON_OPTIONS = LEGACY_JSON_OPTIONS
|
||||
"""The default :class:`JSONOptions` for JSON encoding/decoding.
|
||||
|
||||
The same as :const:`LEGACY_JSON_OPTIONS`. This will change to
|
||||
:const:`RELAXED_JSON_OPTIONS` in a future release.
|
||||
|
||||
.. versionadded:: 3.4
|
||||
"""
|
||||
|
||||
CANONICAL_JSON_OPTIONS = JSONOptions(json_mode=JSONMode.CANONICAL)
|
||||
""":class:`JSONOptions` for Canonical Extended JSON.
|
||||
|
||||
.. seealso:: The documentation for :const:`bson.json_util.JSONMode.CANONICAL`.
|
||||
|
||||
.. versionadded:: 3.5
|
||||
"""
|
||||
|
||||
RELAXED_JSON_OPTIONS = JSONOptions(json_mode=JSONMode.RELAXED)
|
||||
""":class:`JSONOptions` for Relaxed Extended JSON.
|
||||
|
||||
.. seealso:: The documentation for :const:`bson.json_util.JSONMode.RELAXED`.
|
||||
|
||||
.. versionadded:: 3.5
|
||||
"""
|
||||
|
||||
STRICT_JSON_OPTIONS = JSONOptions(
|
||||
strict_number_long=True,
|
||||
datetime_representation=DatetimeRepresentation.ISO8601,
|
||||
strict_uuid=True)
|
||||
"""**DEPRECATED** - :class:`JSONOptions` for MongoDB Extended JSON's *Strict
|
||||
mode* encoding.
|
||||
|
||||
.. versionadded:: 3.4
|
||||
|
||||
.. versionchanged:: 3.5
|
||||
Deprecated. Use :const:`RELAXED_JSON_OPTIONS` or
|
||||
:const:`CANONICAL_JSON_OPTIONS` instead.
|
||||
"""
|
||||
|
||||
|
||||
def dumps(obj, *args, **kwargs):
|
||||
"""Helper function that wraps :func:`json.dumps`.
|
||||
|
||||
Recursive function that handles all BSON types including
|
||||
:class:`~bson.binary.Binary` and :class:`~bson.code.Code`.
|
||||
|
||||
:Parameters:
|
||||
- `json_options`: A :class:`JSONOptions` instance used to modify the
|
||||
encoding of MongoDB Extended JSON types. Defaults to
|
||||
:const:`DEFAULT_JSON_OPTIONS`.
|
||||
|
||||
.. versionchanged:: 3.4
|
||||
Accepts optional parameter `json_options`. See :class:`JSONOptions`.
|
||||
|
||||
.. versionchanged:: 2.7
|
||||
Preserves order when rendering SON, Timestamp, Code, Binary, and DBRef
|
||||
instances.
|
||||
"""
|
||||
json_options = kwargs.pop("json_options", DEFAULT_JSON_OPTIONS)
|
||||
return json.dumps(_json_convert(obj, json_options), *args, **kwargs)
|
||||
|
||||
|
||||
def loads(s, *args, **kwargs):
|
||||
"""Helper function that wraps :func:`json.loads`.
|
||||
|
||||
Automatically passes the object_hook for BSON type conversion.
|
||||
|
||||
Raises ``TypeError``, ``ValueError``, ``KeyError``, or
|
||||
:exc:`~bson.errors.InvalidId` on invalid MongoDB Extended JSON.
|
||||
|
||||
:Parameters:
|
||||
- `json_options`: A :class:`JSONOptions` instance used to modify the
|
||||
decoding of MongoDB Extended JSON types. Defaults to
|
||||
:const:`DEFAULT_JSON_OPTIONS`.
|
||||
|
||||
.. versionchanged:: 3.5
|
||||
Parses Relaxed and Canonical Extended JSON as well as PyMongo's legacy
|
||||
format. Now raises ``TypeError`` or ``ValueError`` when parsing JSON
|
||||
type wrappers with values of the wrong type or any extra keys.
|
||||
|
||||
.. versionchanged:: 3.4
|
||||
Accepts optional parameter `json_options`. See :class:`JSONOptions`.
|
||||
"""
|
||||
json_options = kwargs.pop("json_options", DEFAULT_JSON_OPTIONS)
|
||||
kwargs["object_pairs_hook"] = lambda pairs: object_pairs_hook(
|
||||
pairs, json_options)
|
||||
return json.loads(s, *args, **kwargs)
|
||||
|
||||
|
||||
def _json_convert(obj, json_options=DEFAULT_JSON_OPTIONS):
|
||||
"""Recursive helper method that converts BSON types so they can be
|
||||
converted into json.
|
||||
"""
|
||||
if hasattr(obj, 'iteritems') or hasattr(obj, 'items'): # PY3 support
|
||||
return SON(((k, _json_convert(v, json_options))
|
||||
for k, v in iteritems(obj)))
|
||||
elif hasattr(obj, '__iter__') and not isinstance(obj, (text_type, bytes)):
|
||||
return list((_json_convert(v, json_options) for v in obj))
|
||||
try:
|
||||
return default(obj, json_options)
|
||||
except TypeError:
|
||||
return obj
|
||||
|
||||
|
||||
def object_pairs_hook(pairs, json_options=DEFAULT_JSON_OPTIONS):
|
||||
return object_hook(json_options.document_class(pairs), json_options)
|
||||
|
||||
|
||||
def object_hook(dct, json_options=DEFAULT_JSON_OPTIONS):
|
||||
if "$oid" in dct:
|
||||
return _parse_canonical_oid(dct)
|
||||
if "$ref" in dct:
|
||||
return _parse_canonical_dbref(dct)
|
||||
if "$date" in dct:
|
||||
return _parse_canonical_datetime(dct, json_options)
|
||||
if "$regex" in dct:
|
||||
return _parse_legacy_regex(dct)
|
||||
if "$minKey" in dct:
|
||||
return _parse_canonical_minkey(dct)
|
||||
if "$maxKey" in dct:
|
||||
return _parse_canonical_maxkey(dct)
|
||||
if "$binary" in dct:
|
||||
if "$type" in dct:
|
||||
return _parse_legacy_binary(dct, json_options)
|
||||
else:
|
||||
return _parse_canonical_binary(dct, json_options)
|
||||
if "$code" in dct:
|
||||
return _parse_canonical_code(dct)
|
||||
if "$uuid" in dct:
|
||||
return _parse_legacy_uuid(dct)
|
||||
if "$undefined" in dct:
|
||||
return None
|
||||
if "$numberLong" in dct:
|
||||
return _parse_canonical_int64(dct)
|
||||
if "$timestamp" in dct:
|
||||
tsp = dct["$timestamp"]
|
||||
return Timestamp(tsp["t"], tsp["i"])
|
||||
if "$numberDecimal" in dct:
|
||||
return _parse_canonical_decimal128(dct)
|
||||
if "$dbPointer" in dct:
|
||||
return _parse_canonical_dbpointer(dct)
|
||||
if "$regularExpression" in dct:
|
||||
return _parse_canonical_regex(dct)
|
||||
if "$symbol" in dct:
|
||||
return _parse_canonical_symbol(dct)
|
||||
if "$numberInt" in dct:
|
||||
return _parse_canonical_int32(dct)
|
||||
if "$numberDouble" in dct:
|
||||
return _parse_canonical_double(dct)
|
||||
return dct
|
||||
|
||||
|
||||
def _parse_legacy_regex(doc):
|
||||
pattern = doc["$regex"]
|
||||
# Check if this is the $regex query operator.
|
||||
if isinstance(pattern, Regex):
|
||||
return doc
|
||||
flags = 0
|
||||
# PyMongo always adds $options but some other tools may not.
|
||||
for opt in doc.get("$options", ""):
|
||||
flags |= _RE_OPT_TABLE.get(opt, 0)
|
||||
return Regex(pattern, flags)
|
||||
|
||||
|
||||
def _parse_legacy_uuid(doc):
|
||||
"""Decode a JSON legacy $uuid to Python UUID."""
|
||||
if len(doc) != 1:
|
||||
raise TypeError('Bad $uuid, extra field(s): %s' % (doc,))
|
||||
return uuid.UUID(doc["$uuid"])
|
||||
|
||||
|
||||
def _binary_or_uuid(data, subtype, json_options):
|
||||
# special handling for UUID
|
||||
if subtype == OLD_UUID_SUBTYPE:
|
||||
if json_options.uuid_representation == CSHARP_LEGACY:
|
||||
return uuid.UUID(bytes_le=data)
|
||||
if json_options.uuid_representation == JAVA_LEGACY:
|
||||
data = data[7::-1] + data[:7:-1]
|
||||
return uuid.UUID(bytes=data)
|
||||
if subtype == UUID_SUBTYPE:
|
||||
return uuid.UUID(bytes=data)
|
||||
if PY3 and subtype == 0:
|
||||
return data
|
||||
return Binary(data, subtype)
|
||||
|
||||
|
||||
def _parse_legacy_binary(doc, json_options):
|
||||
if isinstance(doc["$type"], int):
|
||||
doc["$type"] = "%02x" % doc["$type"]
|
||||
subtype = int(doc["$type"], 16)
|
||||
if subtype >= 0xffffff80: # Handle mongoexport values
|
||||
subtype = int(doc["$type"][6:], 16)
|
||||
data = base64.b64decode(doc["$binary"].encode())
|
||||
return _binary_or_uuid(data, subtype, json_options)
|
||||
|
||||
|
||||
def _parse_canonical_binary(doc, json_options):
|
||||
binary = doc["$binary"]
|
||||
b64 = binary["base64"]
|
||||
subtype = binary["subType"]
|
||||
if not isinstance(b64, string_type):
|
||||
raise TypeError('$binary base64 must be a string: %s' % (doc,))
|
||||
if not isinstance(subtype, string_type) or len(subtype) > 2:
|
||||
raise TypeError('$binary subType must be a string at most 2 '
|
||||
'characters: %s' % (doc,))
|
||||
if len(binary) != 2:
|
||||
raise TypeError('$binary must include only "base64" and "subType" '
|
||||
'components: %s' % (doc,))
|
||||
|
||||
data = base64.b64decode(b64.encode())
|
||||
return _binary_or_uuid(data, int(subtype, 16), json_options)
|
||||
|
||||
|
||||
def _parse_canonical_datetime(doc, json_options):
|
||||
"""Decode a JSON datetime to python datetime.datetime."""
|
||||
dtm = doc["$date"]
|
||||
if len(doc) != 1:
|
||||
raise TypeError('Bad $date, extra field(s): %s' % (doc,))
|
||||
# mongoexport 2.6 and newer
|
||||
if isinstance(dtm, string_type):
|
||||
# Parse offset
|
||||
if dtm[-1] == 'Z':
|
||||
dt = dtm[:-1]
|
||||
offset = 'Z'
|
||||
elif dtm[-6] in ('+', '-') and dtm[-3] == ':':
|
||||
# (+|-)HH:MM
|
||||
dt = dtm[:-6]
|
||||
offset = dtm[-6:]
|
||||
elif dtm[-5] in ('+', '-'):
|
||||
# (+|-)HHMM
|
||||
dt = dtm[:-5]
|
||||
offset = dtm[-5:]
|
||||
elif dtm[-3] in ('+', '-'):
|
||||
# (+|-)HH
|
||||
dt = dtm[:-3]
|
||||
offset = dtm[-3:]
|
||||
else:
|
||||
dt = dtm
|
||||
offset = ''
|
||||
|
||||
# Parse the optional factional seconds portion.
|
||||
dot_index = dt.rfind('.')
|
||||
microsecond = 0
|
||||
if dot_index != -1:
|
||||
microsecond = int(float(dt[dot_index:]) * 1000000)
|
||||
dt = dt[:dot_index]
|
||||
|
||||
aware = datetime.datetime.strptime(
|
||||
dt, "%Y-%m-%dT%H:%M:%S").replace(microsecond=microsecond,
|
||||
tzinfo=utc)
|
||||
|
||||
if offset and offset != 'Z':
|
||||
if len(offset) == 6:
|
||||
hours, minutes = offset[1:].split(':')
|
||||
secs = (int(hours) * 3600 + int(minutes) * 60)
|
||||
elif len(offset) == 5:
|
||||
secs = (int(offset[1:3]) * 3600 + int(offset[3:]) * 60)
|
||||
elif len(offset) == 3:
|
||||
secs = int(offset[1:3]) * 3600
|
||||
if offset[0] == "-":
|
||||
secs *= -1
|
||||
aware = aware - datetime.timedelta(seconds=secs)
|
||||
|
||||
if json_options.tz_aware:
|
||||
if json_options.tzinfo:
|
||||
aware = aware.astimezone(json_options.tzinfo)
|
||||
return aware
|
||||
else:
|
||||
return aware.replace(tzinfo=None)
|
||||
return bson._millis_to_datetime(int(dtm), json_options)
|
||||
|
||||
|
||||
def _parse_canonical_oid(doc):
|
||||
"""Decode a JSON ObjectId to bson.objectid.ObjectId."""
|
||||
if len(doc) != 1:
|
||||
raise TypeError('Bad $oid, extra field(s): %s' % (doc,))
|
||||
return ObjectId(doc['$oid'])
|
||||
|
||||
|
||||
def _parse_canonical_symbol(doc):
|
||||
"""Decode a JSON symbol to Python string."""
|
||||
symbol = doc['$symbol']
|
||||
if len(doc) != 1:
|
||||
raise TypeError('Bad $symbol, extra field(s): %s' % (doc,))
|
||||
return text_type(symbol)
|
||||
|
||||
|
||||
def _parse_canonical_code(doc):
|
||||
"""Decode a JSON code to bson.code.Code."""
|
||||
for key in doc:
|
||||
if key not in ('$code', '$scope'):
|
||||
raise TypeError('Bad $code, extra field(s): %s' % (doc,))
|
||||
return Code(doc['$code'], scope=doc.get('$scope'))
|
||||
|
||||
|
||||
def _parse_canonical_regex(doc):
|
||||
"""Decode a JSON regex to bson.regex.Regex."""
|
||||
regex = doc['$regularExpression']
|
||||
if len(doc) != 1:
|
||||
raise TypeError('Bad $regularExpression, extra field(s): %s' % (doc,))
|
||||
if len(regex) != 2:
|
||||
raise TypeError('Bad $regularExpression must include only "pattern"'
|
||||
'and "options" components: %s' % (doc,))
|
||||
return Regex(regex['pattern'], regex['options'])
|
||||
|
||||
|
||||
def _parse_canonical_dbref(doc):
|
||||
"""Decode a JSON DBRef to bson.dbref.DBRef."""
|
||||
for key in doc:
|
||||
if key.startswith('$') and key not in _DBREF_KEYS:
|
||||
# Other keys start with $, so dct cannot be parsed as a DBRef.
|
||||
return doc
|
||||
return DBRef(doc.pop('$ref'), doc.pop('$id'),
|
||||
database=doc.pop('$db', None), **doc)
|
||||
|
||||
|
||||
def _parse_canonical_dbpointer(doc):
|
||||
"""Decode a JSON (deprecated) DBPointer to bson.dbref.DBRef."""
|
||||
dbref = doc['$dbPointer']
|
||||
if len(doc) != 1:
|
||||
raise TypeError('Bad $dbPointer, extra field(s): %s' % (doc,))
|
||||
if isinstance(dbref, DBRef):
|
||||
dbref_doc = dbref.as_doc()
|
||||
# DBPointer must not contain $db in its value.
|
||||
if dbref.database is not None:
|
||||
raise TypeError(
|
||||
'Bad $dbPointer, extra field $db: %s' % (dbref_doc,))
|
||||
if not isinstance(dbref.id, ObjectId):
|
||||
raise TypeError(
|
||||
'Bad $dbPointer, $id must be an ObjectId: %s' % (dbref_doc,))
|
||||
if len(dbref_doc) != 2:
|
||||
raise TypeError(
|
||||
'Bad $dbPointer, extra field(s) in DBRef: %s' % (dbref_doc,))
|
||||
return dbref
|
||||
else:
|
||||
raise TypeError('Bad $dbPointer, expected a DBRef: %s' % (doc,))
|
||||
|
||||
|
||||
def _parse_canonical_int32(doc):
|
||||
"""Decode a JSON int32 to python int."""
|
||||
i_str = doc['$numberInt']
|
||||
if len(doc) != 1:
|
||||
raise TypeError('Bad $numberInt, extra field(s): %s' % (doc,))
|
||||
if not isinstance(i_str, string_type):
|
||||
raise TypeError('$numberInt must be string: %s' % (doc,))
|
||||
return int(i_str)
|
||||
|
||||
|
||||
def _parse_canonical_int64(doc):
|
||||
"""Decode a JSON int64 to bson.int64.Int64."""
|
||||
l_str = doc['$numberLong']
|
||||
if len(doc) != 1:
|
||||
raise TypeError('Bad $numberLong, extra field(s): %s' % (doc,))
|
||||
return Int64(l_str)
|
||||
|
||||
|
||||
def _parse_canonical_double(doc):
|
||||
"""Decode a JSON double to python float."""
|
||||
d_str = doc['$numberDouble']
|
||||
if len(doc) != 1:
|
||||
raise TypeError('Bad $numberDouble, extra field(s): %s' % (doc,))
|
||||
if not isinstance(d_str, string_type):
|
||||
raise TypeError('$numberDouble must be string: %s' % (doc,))
|
||||
return float(d_str)
|
||||
|
||||
|
||||
def _parse_canonical_decimal128(doc):
|
||||
"""Decode a JSON decimal128 to bson.decimal128.Decimal128."""
|
||||
d_str = doc['$numberDecimal']
|
||||
if len(doc) != 1:
|
||||
raise TypeError('Bad $numberDecimal, extra field(s): %s' % (doc,))
|
||||
if not isinstance(d_str, string_type):
|
||||
raise TypeError('$numberDecimal must be string: %s' % (doc,))
|
||||
return Decimal128(d_str)
|
||||
|
||||
|
||||
def _parse_canonical_minkey(doc):
|
||||
"""Decode a JSON MinKey to bson.min_key.MinKey."""
|
||||
if doc['$minKey'] is not 1:
|
||||
raise TypeError('$minKey value must be 1: %s' % (doc,))
|
||||
if len(doc) != 1:
|
||||
raise TypeError('Bad $minKey, extra field(s): %s' % (doc,))
|
||||
return MinKey()
|
||||
|
||||
|
||||
def _parse_canonical_maxkey(doc):
|
||||
"""Decode a JSON MaxKey to bson.max_key.MaxKey."""
|
||||
if doc['$maxKey'] is not 1:
|
||||
raise TypeError('$maxKey value must be 1: %s', (doc,))
|
||||
if len(doc) != 1:
|
||||
raise TypeError('Bad $minKey, extra field(s): %s' % (doc,))
|
||||
return MaxKey()
|
||||
|
||||
|
||||
def _encode_binary(data, subtype, json_options):
|
||||
if json_options.json_mode == JSONMode.LEGACY:
|
||||
return SON([
|
||||
('$binary', base64.b64encode(data).decode()),
|
||||
('$type', "%02x" % subtype)])
|
||||
return {'$binary': SON([
|
||||
('base64', base64.b64encode(data).decode()),
|
||||
('subType', "%02x" % subtype)])}
|
||||
|
||||
|
||||
def default(obj, json_options=DEFAULT_JSON_OPTIONS):
|
||||
# We preserve key order when rendering SON, DBRef, etc. as JSON by
|
||||
# returning a SON for those types instead of a dict.
|
||||
if isinstance(obj, ObjectId):
|
||||
return {"$oid": str(obj)}
|
||||
if isinstance(obj, DBRef):
|
||||
return _json_convert(obj.as_doc(), json_options=json_options)
|
||||
if isinstance(obj, datetime.datetime):
|
||||
if (json_options.datetime_representation ==
|
||||
DatetimeRepresentation.ISO8601):
|
||||
if not obj.tzinfo:
|
||||
obj = obj.replace(tzinfo=utc)
|
||||
if obj >= EPOCH_AWARE:
|
||||
off = obj.tzinfo.utcoffset(obj)
|
||||
if (off.days, off.seconds, off.microseconds) == (0, 0, 0):
|
||||
tz_string = 'Z'
|
||||
else:
|
||||
tz_string = obj.strftime('%z')
|
||||
millis = int(obj.microsecond / 1000)
|
||||
fracsecs = ".%03d" % (millis,) if millis else ""
|
||||
return {"$date": "%s%s%s" % (
|
||||
obj.strftime("%Y-%m-%dT%H:%M:%S"), fracsecs, tz_string)}
|
||||
|
||||
millis = bson._datetime_to_millis(obj)
|
||||
if (json_options.datetime_representation ==
|
||||
DatetimeRepresentation.LEGACY):
|
||||
return {"$date": millis}
|
||||
return {"$date": {"$numberLong": str(millis)}}
|
||||
if json_options.strict_number_long and isinstance(obj, Int64):
|
||||
return {"$numberLong": str(obj)}
|
||||
if isinstance(obj, (RE_TYPE, Regex)):
|
||||
flags = ""
|
||||
if obj.flags & re.IGNORECASE:
|
||||
flags += "i"
|
||||
if obj.flags & re.LOCALE:
|
||||
flags += "l"
|
||||
if obj.flags & re.MULTILINE:
|
||||
flags += "m"
|
||||
if obj.flags & re.DOTALL:
|
||||
flags += "s"
|
||||
if obj.flags & re.UNICODE:
|
||||
flags += "u"
|
||||
if obj.flags & re.VERBOSE:
|
||||
flags += "x"
|
||||
if isinstance(obj.pattern, text_type):
|
||||
pattern = obj.pattern
|
||||
else:
|
||||
pattern = obj.pattern.decode('utf-8')
|
||||
if json_options.json_mode == JSONMode.LEGACY:
|
||||
return SON([("$regex", pattern), ("$options", flags)])
|
||||
return {'$regularExpression': SON([("pattern", pattern),
|
||||
("options", flags)])}
|
||||
if isinstance(obj, MinKey):
|
||||
return {"$minKey": 1}
|
||||
if isinstance(obj, MaxKey):
|
||||
return {"$maxKey": 1}
|
||||
if isinstance(obj, Timestamp):
|
||||
return {"$timestamp": SON([("t", obj.time), ("i", obj.inc)])}
|
||||
if isinstance(obj, Code):
|
||||
if obj.scope is None:
|
||||
return {'$code': str(obj)}
|
||||
return SON([
|
||||
('$code', str(obj)),
|
||||
('$scope', _json_convert(obj.scope, json_options))])
|
||||
if isinstance(obj, Binary):
|
||||
return _encode_binary(obj, obj.subtype, json_options)
|
||||
if PY3 and isinstance(obj, bytes):
|
||||
return _encode_binary(obj, 0, json_options)
|
||||
if isinstance(obj, uuid.UUID):
|
||||
if json_options.strict_uuid:
|
||||
data = obj.bytes
|
||||
subtype = OLD_UUID_SUBTYPE
|
||||
if json_options.uuid_representation == CSHARP_LEGACY:
|
||||
data = obj.bytes_le
|
||||
elif json_options.uuid_representation == JAVA_LEGACY:
|
||||
data = data[7::-1] + data[:7:-1]
|
||||
elif json_options.uuid_representation == UUID_SUBTYPE:
|
||||
subtype = UUID_SUBTYPE
|
||||
return _encode_binary(data, subtype, json_options)
|
||||
else:
|
||||
return {"$uuid": obj.hex}
|
||||
if isinstance(obj, Decimal128):
|
||||
return {"$numberDecimal": str(obj)}
|
||||
if isinstance(obj, bool):
|
||||
return obj
|
||||
if (json_options.json_mode == JSONMode.CANONICAL and
|
||||
isinstance(obj, integer_types)):
|
||||
if -2 ** 31 <= obj < 2 ** 31:
|
||||
return {'$numberInt': text_type(obj)}
|
||||
return {'$numberLong': text_type(obj)}
|
||||
if json_options.json_mode != JSONMode.LEGACY and isinstance(obj, float):
|
||||
if math.isnan(obj):
|
||||
return {'$numberDouble': 'NaN'}
|
||||
elif math.isinf(obj):
|
||||
representation = 'Infinity' if obj > 0 else '-Infinity'
|
||||
return {'$numberDouble': representation}
|
||||
elif json_options.json_mode == JSONMode.CANONICAL:
|
||||
# repr() will return the shortest string guaranteed to produce the
|
||||
# original value, when float() is called on it. str produces a
|
||||
# shorter string in Python 2.
|
||||
return {'$numberDouble': text_type(repr(obj))}
|
||||
raise TypeError("%r is not JSON serializable" % obj)
|
||||
50
venv/lib/python3.8/site-packages/bson/max_key.py
Normal file
50
venv/lib/python3.8/site-packages/bson/max_key.py
Normal file
@@ -0,0 +1,50 @@
|
||||
# Copyright 2010-present MongoDB, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Representation for the MongoDB internal MaxKey type.
|
||||
"""
|
||||
|
||||
|
||||
class MaxKey(object):
|
||||
"""MongoDB internal MaxKey type.
|
||||
|
||||
.. versionchanged:: 2.7
|
||||
``MaxKey`` now implements comparison operators.
|
||||
"""
|
||||
|
||||
_type_marker = 127
|
||||
|
||||
def __eq__(self, other):
|
||||
return isinstance(other, MaxKey)
|
||||
|
||||
def __hash__(self):
|
||||
return hash(self._type_marker)
|
||||
|
||||
def __ne__(self, other):
|
||||
return not self == other
|
||||
|
||||
def __le__(self, other):
|
||||
return isinstance(other, MaxKey)
|
||||
|
||||
def __lt__(self, dummy):
|
||||
return False
|
||||
|
||||
def __ge__(self, dummy):
|
||||
return True
|
||||
|
||||
def __gt__(self, other):
|
||||
return not isinstance(other, MaxKey)
|
||||
|
||||
def __repr__(self):
|
||||
return "MaxKey()"
|
||||
50
venv/lib/python3.8/site-packages/bson/min_key.py
Normal file
50
venv/lib/python3.8/site-packages/bson/min_key.py
Normal file
@@ -0,0 +1,50 @@
|
||||
# Copyright 2010-present MongoDB, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Representation for the MongoDB internal MinKey type.
|
||||
"""
|
||||
|
||||
|
||||
class MinKey(object):
|
||||
"""MongoDB internal MinKey type.
|
||||
|
||||
.. versionchanged:: 2.7
|
||||
``MinKey`` now implements comparison operators.
|
||||
"""
|
||||
|
||||
_type_marker = 255
|
||||
|
||||
def __eq__(self, other):
|
||||
return isinstance(other, MinKey)
|
||||
|
||||
def __hash__(self):
|
||||
return hash(self._type_marker)
|
||||
|
||||
def __ne__(self, other):
|
||||
return not self == other
|
||||
|
||||
def __le__(self, dummy):
|
||||
return True
|
||||
|
||||
def __lt__(self, other):
|
||||
return not isinstance(other, MinKey)
|
||||
|
||||
def __ge__(self, other):
|
||||
return isinstance(other, MinKey)
|
||||
|
||||
def __gt__(self, dummy):
|
||||
return False
|
||||
|
||||
def __repr__(self):
|
||||
return "MinKey()"
|
||||
299
venv/lib/python3.8/site-packages/bson/objectid.py
Normal file
299
venv/lib/python3.8/site-packages/bson/objectid.py
Normal file
@@ -0,0 +1,299 @@
|
||||
# Copyright 2009-2015 MongoDB, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Tools for working with MongoDB `ObjectIds
|
||||
<http://dochub.mongodb.org/core/objectids>`_.
|
||||
"""
|
||||
|
||||
import binascii
|
||||
import calendar
|
||||
import datetime
|
||||
import os
|
||||
import struct
|
||||
import threading
|
||||
import time
|
||||
|
||||
from random import SystemRandom
|
||||
|
||||
from bson.errors import InvalidId
|
||||
from bson.py3compat import PY3, bytes_from_hex, string_type, text_type
|
||||
from bson.tz_util import utc
|
||||
|
||||
|
||||
_MAX_COUNTER_VALUE = 0xFFFFFF
|
||||
|
||||
|
||||
def _raise_invalid_id(oid):
|
||||
raise InvalidId(
|
||||
"%r is not a valid ObjectId, it must be a 12-byte input"
|
||||
" or a 24-character hex string" % oid)
|
||||
|
||||
|
||||
def _random_bytes():
|
||||
"""Get the 5-byte random field of an ObjectId."""
|
||||
return os.urandom(5)
|
||||
|
||||
|
||||
class ObjectId(object):
|
||||
"""A MongoDB ObjectId.
|
||||
"""
|
||||
|
||||
_pid = os.getpid()
|
||||
|
||||
_inc = SystemRandom().randint(0, _MAX_COUNTER_VALUE)
|
||||
_inc_lock = threading.Lock()
|
||||
|
||||
__random = _random_bytes()
|
||||
|
||||
__slots__ = ('__id',)
|
||||
|
||||
_type_marker = 7
|
||||
|
||||
def __init__(self, oid=None):
|
||||
"""Initialize a new ObjectId.
|
||||
|
||||
An ObjectId is a 12-byte unique identifier consisting of:
|
||||
|
||||
- a 4-byte value representing the seconds since the Unix epoch,
|
||||
- a 5-byte random value,
|
||||
- a 3-byte counter, starting with a random value.
|
||||
|
||||
By default, ``ObjectId()`` creates a new unique identifier. The
|
||||
optional parameter `oid` can be an :class:`ObjectId`, or any 12
|
||||
:class:`bytes` or, in Python 2, any 12-character :class:`str`.
|
||||
|
||||
For example, the 12 bytes b'foo-bar-quux' do not follow the ObjectId
|
||||
specification but they are acceptable input::
|
||||
|
||||
>>> ObjectId(b'foo-bar-quux')
|
||||
ObjectId('666f6f2d6261722d71757578')
|
||||
|
||||
`oid` can also be a :class:`unicode` or :class:`str` of 24 hex digits::
|
||||
|
||||
>>> ObjectId('0123456789ab0123456789ab')
|
||||
ObjectId('0123456789ab0123456789ab')
|
||||
>>>
|
||||
>>> # A u-prefixed unicode literal:
|
||||
>>> ObjectId(u'0123456789ab0123456789ab')
|
||||
ObjectId('0123456789ab0123456789ab')
|
||||
|
||||
Raises :class:`~bson.errors.InvalidId` if `oid` is not 12 bytes nor
|
||||
24 hex digits, or :class:`TypeError` if `oid` is not an accepted type.
|
||||
|
||||
:Parameters:
|
||||
- `oid` (optional): a valid ObjectId.
|
||||
|
||||
.. mongodoc:: objectids
|
||||
|
||||
.. versionchanged:: 3.8
|
||||
:class:`~bson.objectid.ObjectId` now implements the `ObjectID
|
||||
specification version 0.2
|
||||
<https://github.com/mongodb/specifications/blob/master/source/
|
||||
objectid.rst>`_.
|
||||
"""
|
||||
if oid is None:
|
||||
self.__generate()
|
||||
elif isinstance(oid, bytes) and len(oid) == 12:
|
||||
self.__id = oid
|
||||
else:
|
||||
self.__validate(oid)
|
||||
|
||||
@classmethod
|
||||
def from_datetime(cls, generation_time):
|
||||
"""Create a dummy ObjectId instance with a specific generation time.
|
||||
|
||||
This method is useful for doing range queries on a field
|
||||
containing :class:`ObjectId` instances.
|
||||
|
||||
.. warning::
|
||||
It is not safe to insert a document containing an ObjectId
|
||||
generated using this method. This method deliberately
|
||||
eliminates the uniqueness guarantee that ObjectIds
|
||||
generally provide. ObjectIds generated with this method
|
||||
should be used exclusively in queries.
|
||||
|
||||
`generation_time` will be converted to UTC. Naive datetime
|
||||
instances will be treated as though they already contain UTC.
|
||||
|
||||
An example using this helper to get documents where ``"_id"``
|
||||
was generated before January 1, 2010 would be:
|
||||
|
||||
>>> gen_time = datetime.datetime(2010, 1, 1)
|
||||
>>> dummy_id = ObjectId.from_datetime(gen_time)
|
||||
>>> result = collection.find({"_id": {"$lt": dummy_id}})
|
||||
|
||||
:Parameters:
|
||||
- `generation_time`: :class:`~datetime.datetime` to be used
|
||||
as the generation time for the resulting ObjectId.
|
||||
"""
|
||||
if generation_time.utcoffset() is not None:
|
||||
generation_time = generation_time - generation_time.utcoffset()
|
||||
timestamp = calendar.timegm(generation_time.timetuple())
|
||||
oid = struct.pack(
|
||||
">I", int(timestamp)) + b"\x00\x00\x00\x00\x00\x00\x00\x00"
|
||||
return cls(oid)
|
||||
|
||||
@classmethod
|
||||
def is_valid(cls, oid):
|
||||
"""Checks if a `oid` string is valid or not.
|
||||
|
||||
:Parameters:
|
||||
- `oid`: the object id to validate
|
||||
|
||||
.. versionadded:: 2.3
|
||||
"""
|
||||
if not oid:
|
||||
return False
|
||||
|
||||
try:
|
||||
ObjectId(oid)
|
||||
return True
|
||||
except (InvalidId, TypeError):
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def _random(cls):
|
||||
"""Generate a 5-byte random number once per process.
|
||||
"""
|
||||
pid = os.getpid()
|
||||
if pid != cls._pid:
|
||||
cls._pid = pid
|
||||
cls.__random = _random_bytes()
|
||||
return cls.__random
|
||||
|
||||
def __generate(self):
|
||||
"""Generate a new value for this ObjectId.
|
||||
"""
|
||||
|
||||
# 4 bytes current time
|
||||
oid = struct.pack(">I", int(time.time()))
|
||||
|
||||
# 5 bytes random
|
||||
oid += ObjectId._random()
|
||||
|
||||
# 3 bytes inc
|
||||
with ObjectId._inc_lock:
|
||||
oid += struct.pack(">I", ObjectId._inc)[1:4]
|
||||
ObjectId._inc = (ObjectId._inc + 1) % (_MAX_COUNTER_VALUE + 1)
|
||||
|
||||
self.__id = oid
|
||||
|
||||
def __validate(self, oid):
|
||||
"""Validate and use the given id for this ObjectId.
|
||||
|
||||
Raises TypeError if id is not an instance of
|
||||
(:class:`basestring` (:class:`str` or :class:`bytes`
|
||||
in python 3), ObjectId) and InvalidId if it is not a
|
||||
valid ObjectId.
|
||||
|
||||
:Parameters:
|
||||
- `oid`: a valid ObjectId
|
||||
"""
|
||||
if isinstance(oid, ObjectId):
|
||||
self.__id = oid.binary
|
||||
# bytes or unicode in python 2, str in python 3
|
||||
elif isinstance(oid, string_type):
|
||||
if len(oid) == 24:
|
||||
try:
|
||||
self.__id = bytes_from_hex(oid)
|
||||
except (TypeError, ValueError):
|
||||
_raise_invalid_id(oid)
|
||||
else:
|
||||
_raise_invalid_id(oid)
|
||||
else:
|
||||
raise TypeError("id must be an instance of (bytes, %s, ObjectId), "
|
||||
"not %s" % (text_type.__name__, type(oid)))
|
||||
|
||||
@property
|
||||
def binary(self):
|
||||
"""12-byte binary representation of this ObjectId.
|
||||
"""
|
||||
return self.__id
|
||||
|
||||
@property
|
||||
def generation_time(self):
|
||||
"""A :class:`datetime.datetime` instance representing the time of
|
||||
generation for this :class:`ObjectId`.
|
||||
|
||||
The :class:`datetime.datetime` is timezone aware, and
|
||||
represents the generation time in UTC. It is precise to the
|
||||
second.
|
||||
"""
|
||||
timestamp = struct.unpack(">I", self.__id[0:4])[0]
|
||||
return datetime.datetime.fromtimestamp(timestamp, utc)
|
||||
|
||||
def __getstate__(self):
|
||||
"""return value of object for pickling.
|
||||
needed explicitly because __slots__() defined.
|
||||
"""
|
||||
return self.__id
|
||||
|
||||
def __setstate__(self, value):
|
||||
"""explicit state set from pickling
|
||||
"""
|
||||
# Provide backwards compatability with OIDs
|
||||
# pickled with pymongo-1.9 or older.
|
||||
if isinstance(value, dict):
|
||||
oid = value["_ObjectId__id"]
|
||||
else:
|
||||
oid = value
|
||||
# ObjectIds pickled in python 2.x used `str` for __id.
|
||||
# In python 3.x this has to be converted to `bytes`
|
||||
# by encoding latin-1.
|
||||
if PY3 and isinstance(oid, text_type):
|
||||
self.__id = oid.encode('latin-1')
|
||||
else:
|
||||
self.__id = oid
|
||||
|
||||
def __str__(self):
|
||||
if PY3:
|
||||
return binascii.hexlify(self.__id).decode()
|
||||
return binascii.hexlify(self.__id)
|
||||
|
||||
def __repr__(self):
|
||||
return "ObjectId('%s')" % (str(self),)
|
||||
|
||||
def __eq__(self, other):
|
||||
if isinstance(other, ObjectId):
|
||||
return self.__id == other.binary
|
||||
return NotImplemented
|
||||
|
||||
def __ne__(self, other):
|
||||
if isinstance(other, ObjectId):
|
||||
return self.__id != other.binary
|
||||
return NotImplemented
|
||||
|
||||
def __lt__(self, other):
|
||||
if isinstance(other, ObjectId):
|
||||
return self.__id < other.binary
|
||||
return NotImplemented
|
||||
|
||||
def __le__(self, other):
|
||||
if isinstance(other, ObjectId):
|
||||
return self.__id <= other.binary
|
||||
return NotImplemented
|
||||
|
||||
def __gt__(self, other):
|
||||
if isinstance(other, ObjectId):
|
||||
return self.__id > other.binary
|
||||
return NotImplemented
|
||||
|
||||
def __ge__(self, other):
|
||||
if isinstance(other, ObjectId):
|
||||
return self.__id >= other.binary
|
||||
return NotImplemented
|
||||
|
||||
def __hash__(self):
|
||||
"""Get a hash value for this :class:`ObjectId`."""
|
||||
return hash(self.__id)
|
||||
107
venv/lib/python3.8/site-packages/bson/py3compat.py
Normal file
107
venv/lib/python3.8/site-packages/bson/py3compat.py
Normal file
@@ -0,0 +1,107 @@
|
||||
# Copyright 2009-present MongoDB, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License"); you
|
||||
# may not use this file except in compliance with the License. You
|
||||
# may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
# implied. See the License for the specific language governing
|
||||
# permissions and limitations under the License.
|
||||
|
||||
"""Utility functions and definitions for python3 compatibility."""
|
||||
|
||||
import sys
|
||||
|
||||
PY3 = sys.version_info[0] == 3
|
||||
|
||||
if PY3:
|
||||
import codecs
|
||||
import collections.abc as abc
|
||||
import _thread as thread
|
||||
from abc import ABC, abstractmethod
|
||||
from io import BytesIO as StringIO
|
||||
|
||||
def abstractproperty(func):
|
||||
return property(abstractmethod(func))
|
||||
|
||||
MAXSIZE = sys.maxsize
|
||||
|
||||
imap = map
|
||||
|
||||
def b(s):
|
||||
# BSON and socket operations deal in binary data. In
|
||||
# python 3 that means instances of `bytes`. In python
|
||||
# 2.7 you can create an alias for `bytes` using
|
||||
# the b prefix (e.g. b'foo').
|
||||
# See http://python3porting.com/problems.html#nicer-solutions
|
||||
return codecs.latin_1_encode(s)[0]
|
||||
|
||||
def bytes_from_hex(h):
|
||||
return bytes.fromhex(h)
|
||||
|
||||
def iteritems(d):
|
||||
return iter(d.items())
|
||||
|
||||
def itervalues(d):
|
||||
return iter(d.values())
|
||||
|
||||
def reraise(exctype, value, trace=None):
|
||||
raise exctype(str(value)).with_traceback(trace)
|
||||
|
||||
def reraise_instance(exc_instance, trace=None):
|
||||
raise exc_instance.with_traceback(trace)
|
||||
|
||||
def _unicode(s):
|
||||
return s
|
||||
|
||||
text_type = str
|
||||
string_type = str
|
||||
integer_types = int
|
||||
else:
|
||||
import collections as abc
|
||||
import thread
|
||||
from abc import ABCMeta, abstractproperty
|
||||
|
||||
from itertools import imap
|
||||
try:
|
||||
from cStringIO import StringIO
|
||||
except ImportError:
|
||||
from StringIO import StringIO
|
||||
|
||||
ABC = ABCMeta('ABC', (object,), {})
|
||||
|
||||
MAXSIZE = sys.maxint
|
||||
|
||||
def b(s):
|
||||
# See comments above. In python 2.x b('foo') is just 'foo'.
|
||||
return s
|
||||
|
||||
def bytes_from_hex(h):
|
||||
return h.decode('hex')
|
||||
|
||||
def iteritems(d):
|
||||
return d.iteritems()
|
||||
|
||||
def itervalues(d):
|
||||
return d.itervalues()
|
||||
|
||||
def reraise(exctype, value, trace=None):
|
||||
_reraise(exctype, str(value), trace)
|
||||
|
||||
def reraise_instance(exc_instance, trace=None):
|
||||
_reraise(exc_instance, None, trace)
|
||||
|
||||
# "raise x, y, z" raises SyntaxError in Python 3
|
||||
exec("""def _reraise(exc, value, trace):
|
||||
raise exc, value, trace
|
||||
""")
|
||||
|
||||
_unicode = unicode
|
||||
|
||||
string_type = basestring
|
||||
text_type = unicode
|
||||
integer_types = (int, long)
|
||||
138
venv/lib/python3.8/site-packages/bson/raw_bson.py
Normal file
138
venv/lib/python3.8/site-packages/bson/raw_bson.py
Normal file
@@ -0,0 +1,138 @@
|
||||
# Copyright 2015-present MongoDB, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Tools for representing raw BSON documents.
|
||||
"""
|
||||
|
||||
from bson import _raw_to_dict, _get_object_size
|
||||
from bson.py3compat import abc, iteritems
|
||||
from bson.codec_options import (
|
||||
DEFAULT_CODEC_OPTIONS as DEFAULT, _RAW_BSON_DOCUMENT_MARKER)
|
||||
from bson.son import SON
|
||||
|
||||
|
||||
class RawBSONDocument(abc.Mapping):
|
||||
"""Representation for a MongoDB document that provides access to the raw
|
||||
BSON bytes that compose it.
|
||||
|
||||
Only when a field is accessed or modified within the document does
|
||||
RawBSONDocument decode its bytes.
|
||||
"""
|
||||
|
||||
__slots__ = ('__raw', '__inflated_doc', '__codec_options')
|
||||
_type_marker = _RAW_BSON_DOCUMENT_MARKER
|
||||
|
||||
def __init__(self, bson_bytes, codec_options=None):
|
||||
"""Create a new :class:`RawBSONDocument`
|
||||
|
||||
:class:`RawBSONDocument` is a representation of a BSON document that
|
||||
provides access to the underlying raw BSON bytes. Only when a field is
|
||||
accessed or modified within the document does RawBSONDocument decode
|
||||
its bytes.
|
||||
|
||||
:class:`RawBSONDocument` implements the ``Mapping`` abstract base
|
||||
class from the standard library so it can be used like a read-only
|
||||
``dict``::
|
||||
|
||||
>>> raw_doc = RawBSONDocument(BSON.encode({'_id': 'my_doc'}))
|
||||
>>> raw_doc.raw
|
||||
b'...'
|
||||
>>> raw_doc['_id']
|
||||
'my_doc'
|
||||
|
||||
:Parameters:
|
||||
- `bson_bytes`: the BSON bytes that compose this document
|
||||
- `codec_options` (optional): An instance of
|
||||
:class:`~bson.codec_options.CodecOptions` whose ``document_class``
|
||||
must be :class:`RawBSONDocument`. The default is
|
||||
:attr:`DEFAULT_RAW_BSON_OPTIONS`.
|
||||
|
||||
.. versionchanged:: 3.8
|
||||
:class:`RawBSONDocument` now validates that the ``bson_bytes``
|
||||
passed in represent a single bson document.
|
||||
|
||||
.. versionchanged:: 3.5
|
||||
If a :class:`~bson.codec_options.CodecOptions` is passed in, its
|
||||
`document_class` must be :class:`RawBSONDocument`.
|
||||
"""
|
||||
self.__raw = bson_bytes
|
||||
self.__inflated_doc = None
|
||||
# Can't default codec_options to DEFAULT_RAW_BSON_OPTIONS in signature,
|
||||
# it refers to this class RawBSONDocument.
|
||||
if codec_options is None:
|
||||
codec_options = DEFAULT_RAW_BSON_OPTIONS
|
||||
elif codec_options.document_class is not RawBSONDocument:
|
||||
raise TypeError(
|
||||
"RawBSONDocument cannot use CodecOptions with document "
|
||||
"class %s" % (codec_options.document_class, ))
|
||||
self.__codec_options = codec_options
|
||||
# Validate the bson object size.
|
||||
_get_object_size(bson_bytes, 0, len(bson_bytes))
|
||||
|
||||
@property
|
||||
def raw(self):
|
||||
"""The raw BSON bytes composing this document."""
|
||||
return self.__raw
|
||||
|
||||
def items(self):
|
||||
"""Lazily decode and iterate elements in this document."""
|
||||
return iteritems(self.__inflated)
|
||||
|
||||
@property
|
||||
def __inflated(self):
|
||||
if self.__inflated_doc is None:
|
||||
# We already validated the object's size when this document was
|
||||
# created, so no need to do that again.
|
||||
# Use SON to preserve ordering of elements.
|
||||
self.__inflated_doc = _inflate_bson(
|
||||
self.__raw, self.__codec_options)
|
||||
return self.__inflated_doc
|
||||
|
||||
def __getitem__(self, item):
|
||||
return self.__inflated[item]
|
||||
|
||||
def __iter__(self):
|
||||
return iter(self.__inflated)
|
||||
|
||||
def __len__(self):
|
||||
return len(self.__inflated)
|
||||
|
||||
def __eq__(self, other):
|
||||
if isinstance(other, RawBSONDocument):
|
||||
return self.__raw == other.raw
|
||||
return NotImplemented
|
||||
|
||||
def __repr__(self):
|
||||
return ("RawBSONDocument(%r, codec_options=%r)"
|
||||
% (self.raw, self.__codec_options))
|
||||
|
||||
|
||||
def _inflate_bson(bson_bytes, codec_options):
|
||||
"""Inflates the top level fields of a BSON document.
|
||||
|
||||
:Parameters:
|
||||
- `bson_bytes`: the BSON bytes that compose this document
|
||||
- `codec_options`: An instance of
|
||||
:class:`~bson.codec_options.CodecOptions` whose ``document_class``
|
||||
must be :class:`RawBSONDocument`.
|
||||
"""
|
||||
# Use SON to preserve ordering of elements.
|
||||
return _raw_to_dict(
|
||||
bson_bytes, 4, len(bson_bytes)-1, codec_options, SON())
|
||||
|
||||
|
||||
DEFAULT_RAW_BSON_OPTIONS = DEFAULT.with_options(document_class=RawBSONDocument)
|
||||
"""The default :class:`~bson.codec_options.CodecOptions` for
|
||||
:class:`RawBSONDocument`.
|
||||
"""
|
||||
128
venv/lib/python3.8/site-packages/bson/regex.py
Normal file
128
venv/lib/python3.8/site-packages/bson/regex.py
Normal file
@@ -0,0 +1,128 @@
|
||||
# Copyright 2013-present MongoDB, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Tools for representing MongoDB regular expressions.
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
from bson.son import RE_TYPE
|
||||
from bson.py3compat import string_type, text_type
|
||||
|
||||
|
||||
def str_flags_to_int(str_flags):
|
||||
flags = 0
|
||||
if "i" in str_flags:
|
||||
flags |= re.IGNORECASE
|
||||
if "l" in str_flags:
|
||||
flags |= re.LOCALE
|
||||
if "m" in str_flags:
|
||||
flags |= re.MULTILINE
|
||||
if "s" in str_flags:
|
||||
flags |= re.DOTALL
|
||||
if "u" in str_flags:
|
||||
flags |= re.UNICODE
|
||||
if "x" in str_flags:
|
||||
flags |= re.VERBOSE
|
||||
|
||||
return flags
|
||||
|
||||
|
||||
class Regex(object):
|
||||
"""BSON regular expression data."""
|
||||
_type_marker = 11
|
||||
|
||||
@classmethod
|
||||
def from_native(cls, regex):
|
||||
"""Convert a Python regular expression into a ``Regex`` instance.
|
||||
|
||||
Note that in Python 3, a regular expression compiled from a
|
||||
:class:`str` has the ``re.UNICODE`` flag set. If it is undesirable
|
||||
to store this flag in a BSON regular expression, unset it first::
|
||||
|
||||
>>> pattern = re.compile('.*')
|
||||
>>> regex = Regex.from_native(pattern)
|
||||
>>> regex.flags ^= re.UNICODE
|
||||
>>> db.collection.insert({'pattern': regex})
|
||||
|
||||
:Parameters:
|
||||
- `regex`: A regular expression object from ``re.compile()``.
|
||||
|
||||
.. warning::
|
||||
Python regular expressions use a different syntax and different
|
||||
set of flags than MongoDB, which uses `PCRE`_. A regular
|
||||
expression retrieved from the server may not compile in
|
||||
Python, or may match a different set of strings in Python than
|
||||
when used in a MongoDB query.
|
||||
|
||||
.. _PCRE: http://www.pcre.org/
|
||||
"""
|
||||
if not isinstance(regex, RE_TYPE):
|
||||
raise TypeError(
|
||||
"regex must be a compiled regular expression, not %s"
|
||||
% type(regex))
|
||||
|
||||
return Regex(regex.pattern, regex.flags)
|
||||
|
||||
def __init__(self, pattern, flags=0):
|
||||
"""BSON regular expression data.
|
||||
|
||||
This class is useful to store and retrieve regular expressions that are
|
||||
incompatible with Python's regular expression dialect.
|
||||
|
||||
:Parameters:
|
||||
- `pattern`: string
|
||||
- `flags`: (optional) an integer bitmask, or a string of flag
|
||||
characters like "im" for IGNORECASE and MULTILINE
|
||||
"""
|
||||
if not isinstance(pattern, (text_type, bytes)):
|
||||
raise TypeError("pattern must be a string, not %s" % type(pattern))
|
||||
self.pattern = pattern
|
||||
|
||||
if isinstance(flags, string_type):
|
||||
self.flags = str_flags_to_int(flags)
|
||||
elif isinstance(flags, int):
|
||||
self.flags = flags
|
||||
else:
|
||||
raise TypeError(
|
||||
"flags must be a string or int, not %s" % type(flags))
|
||||
|
||||
def __eq__(self, other):
|
||||
if isinstance(other, Regex):
|
||||
return self.pattern == other.pattern and self.flags == other.flags
|
||||
else:
|
||||
return NotImplemented
|
||||
|
||||
__hash__ = None
|
||||
|
||||
def __ne__(self, other):
|
||||
return not self == other
|
||||
|
||||
def __repr__(self):
|
||||
return "Regex(%r, %r)" % (self.pattern, self.flags)
|
||||
|
||||
def try_compile(self):
|
||||
"""Compile this :class:`Regex` as a Python regular expression.
|
||||
|
||||
.. warning::
|
||||
Python regular expressions use a different syntax and different
|
||||
set of flags than MongoDB, which uses `PCRE`_. A regular
|
||||
expression retrieved from the server may not compile in
|
||||
Python, or may match a different set of strings in Python than
|
||||
when used in a MongoDB query. :meth:`try_compile()` may raise
|
||||
:exc:`re.error`.
|
||||
|
||||
.. _PCRE: http://www.pcre.org/
|
||||
"""
|
||||
return re.compile(self.pattern, self.flags)
|
||||
200
venv/lib/python3.8/site-packages/bson/son.py
Normal file
200
venv/lib/python3.8/site-packages/bson/son.py
Normal file
@@ -0,0 +1,200 @@
|
||||
# Copyright 2009-present MongoDB, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Tools for creating and manipulating SON, the Serialized Ocument Notation.
|
||||
|
||||
Regular dictionaries can be used instead of SON objects, but not when the order
|
||||
of keys is important. A SON object can be used just like a normal Python
|
||||
dictionary."""
|
||||
|
||||
import copy
|
||||
import re
|
||||
|
||||
from bson.py3compat import abc, iteritems
|
||||
|
||||
|
||||
# This sort of sucks, but seems to be as good as it gets...
|
||||
# This is essentially the same as re._pattern_type
|
||||
RE_TYPE = type(re.compile(""))
|
||||
|
||||
|
||||
class SON(dict):
|
||||
"""SON data.
|
||||
|
||||
A subclass of dict that maintains ordering of keys and provides a
|
||||
few extra niceties for dealing with SON. SON provides an API
|
||||
similar to collections.OrderedDict from Python 2.7+.
|
||||
"""
|
||||
|
||||
def __init__(self, data=None, **kwargs):
|
||||
self.__keys = []
|
||||
dict.__init__(self)
|
||||
self.update(data)
|
||||
self.update(kwargs)
|
||||
|
||||
def __new__(cls, *args, **kwargs):
|
||||
instance = super(SON, cls).__new__(cls, *args, **kwargs)
|
||||
instance.__keys = []
|
||||
return instance
|
||||
|
||||
def __repr__(self):
|
||||
result = []
|
||||
for key in self.__keys:
|
||||
result.append("(%r, %r)" % (key, self[key]))
|
||||
return "SON([%s])" % ", ".join(result)
|
||||
|
||||
def __setitem__(self, key, value):
|
||||
if key not in self.__keys:
|
||||
self.__keys.append(key)
|
||||
dict.__setitem__(self, key, value)
|
||||
|
||||
def __delitem__(self, key):
|
||||
self.__keys.remove(key)
|
||||
dict.__delitem__(self, key)
|
||||
|
||||
def keys(self):
|
||||
return list(self.__keys)
|
||||
|
||||
def copy(self):
|
||||
other = SON()
|
||||
other.update(self)
|
||||
return other
|
||||
|
||||
# TODO this is all from UserDict.DictMixin. it could probably be made more
|
||||
# efficient.
|
||||
# second level definitions support higher levels
|
||||
def __iter__(self):
|
||||
for k in self.__keys:
|
||||
yield k
|
||||
|
||||
def has_key(self, key):
|
||||
return key in self.__keys
|
||||
|
||||
# third level takes advantage of second level definitions
|
||||
def iteritems(self):
|
||||
for k in self:
|
||||
yield (k, self[k])
|
||||
|
||||
def iterkeys(self):
|
||||
return self.__iter__()
|
||||
|
||||
# fourth level uses definitions from lower levels
|
||||
def itervalues(self):
|
||||
for _, v in self.iteritems():
|
||||
yield v
|
||||
|
||||
def values(self):
|
||||
return [v for _, v in self.iteritems()]
|
||||
|
||||
def items(self):
|
||||
return [(key, self[key]) for key in self]
|
||||
|
||||
def clear(self):
|
||||
self.__keys = []
|
||||
super(SON, self).clear()
|
||||
|
||||
def setdefault(self, key, default=None):
|
||||
try:
|
||||
return self[key]
|
||||
except KeyError:
|
||||
self[key] = default
|
||||
return default
|
||||
|
||||
def pop(self, key, *args):
|
||||
if len(args) > 1:
|
||||
raise TypeError("pop expected at most 2 arguments, got "\
|
||||
+ repr(1 + len(args)))
|
||||
try:
|
||||
value = self[key]
|
||||
except KeyError:
|
||||
if args:
|
||||
return args[0]
|
||||
raise
|
||||
del self[key]
|
||||
return value
|
||||
|
||||
def popitem(self):
|
||||
try:
|
||||
k, v = next(self.iteritems())
|
||||
except StopIteration:
|
||||
raise KeyError('container is empty')
|
||||
del self[k]
|
||||
return (k, v)
|
||||
|
||||
def update(self, other=None, **kwargs):
|
||||
# Make progressively weaker assumptions about "other"
|
||||
if other is None:
|
||||
pass
|
||||
elif hasattr(other, 'iteritems'): # iteritems saves memory and lookups
|
||||
for k, v in other.iteritems():
|
||||
self[k] = v
|
||||
elif hasattr(other, 'keys'):
|
||||
for k in other.keys():
|
||||
self[k] = other[k]
|
||||
else:
|
||||
for k, v in other:
|
||||
self[k] = v
|
||||
if kwargs:
|
||||
self.update(kwargs)
|
||||
|
||||
def get(self, key, default=None):
|
||||
try:
|
||||
return self[key]
|
||||
except KeyError:
|
||||
return default
|
||||
|
||||
def __eq__(self, other):
|
||||
"""Comparison to another SON is order-sensitive while comparison to a
|
||||
regular dictionary is order-insensitive.
|
||||
"""
|
||||
if isinstance(other, SON):
|
||||
return len(self) == len(other) and self.items() == other.items()
|
||||
return self.to_dict() == other
|
||||
|
||||
def __ne__(self, other):
|
||||
return not self == other
|
||||
|
||||
def __len__(self):
|
||||
return len(self.__keys)
|
||||
|
||||
def to_dict(self):
|
||||
"""Convert a SON document to a normal Python dictionary instance.
|
||||
|
||||
This is trickier than just *dict(...)* because it needs to be
|
||||
recursive.
|
||||
"""
|
||||
|
||||
def transform_value(value):
|
||||
if isinstance(value, list):
|
||||
return [transform_value(v) for v in value]
|
||||
elif isinstance(value, abc.Mapping):
|
||||
return dict([
|
||||
(k, transform_value(v))
|
||||
for k, v in iteritems(value)])
|
||||
else:
|
||||
return value
|
||||
|
||||
return transform_value(dict(self))
|
||||
|
||||
def __deepcopy__(self, memo):
|
||||
out = SON()
|
||||
val_id = id(self)
|
||||
if val_id in memo:
|
||||
return memo.get(val_id)
|
||||
memo[val_id] = out
|
||||
for k, v in self.iteritems():
|
||||
if not isinstance(v, RE_TYPE):
|
||||
v = copy.deepcopy(v, memo)
|
||||
out[k] = v
|
||||
return out
|
||||
120
venv/lib/python3.8/site-packages/bson/timestamp.py
Normal file
120
venv/lib/python3.8/site-packages/bson/timestamp.py
Normal file
@@ -0,0 +1,120 @@
|
||||
# Copyright 2010-2015 MongoDB, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Tools for representing MongoDB internal Timestamps.
|
||||
"""
|
||||
|
||||
import calendar
|
||||
import datetime
|
||||
|
||||
from bson.py3compat import integer_types
|
||||
from bson.tz_util import utc
|
||||
|
||||
UPPERBOUND = 4294967296
|
||||
|
||||
|
||||
class Timestamp(object):
|
||||
"""MongoDB internal timestamps used in the opLog.
|
||||
"""
|
||||
|
||||
_type_marker = 17
|
||||
|
||||
def __init__(self, time, inc):
|
||||
"""Create a new :class:`Timestamp`.
|
||||
|
||||
This class is only for use with the MongoDB opLog. If you need
|
||||
to store a regular timestamp, please use a
|
||||
:class:`~datetime.datetime`.
|
||||
|
||||
Raises :class:`TypeError` if `time` is not an instance of
|
||||
:class: `int` or :class:`~datetime.datetime`, or `inc` is not
|
||||
an instance of :class:`int`. Raises :class:`ValueError` if
|
||||
`time` or `inc` is not in [0, 2**32).
|
||||
|
||||
:Parameters:
|
||||
- `time`: time in seconds since epoch UTC, or a naive UTC
|
||||
:class:`~datetime.datetime`, or an aware
|
||||
:class:`~datetime.datetime`
|
||||
- `inc`: the incrementing counter
|
||||
"""
|
||||
if isinstance(time, datetime.datetime):
|
||||
if time.utcoffset() is not None:
|
||||
time = time - time.utcoffset()
|
||||
time = int(calendar.timegm(time.timetuple()))
|
||||
if not isinstance(time, integer_types):
|
||||
raise TypeError("time must be an instance of int")
|
||||
if not isinstance(inc, integer_types):
|
||||
raise TypeError("inc must be an instance of int")
|
||||
if not 0 <= time < UPPERBOUND:
|
||||
raise ValueError("time must be contained in [0, 2**32)")
|
||||
if not 0 <= inc < UPPERBOUND:
|
||||
raise ValueError("inc must be contained in [0, 2**32)")
|
||||
|
||||
self.__time = time
|
||||
self.__inc = inc
|
||||
|
||||
@property
|
||||
def time(self):
|
||||
"""Get the time portion of this :class:`Timestamp`.
|
||||
"""
|
||||
return self.__time
|
||||
|
||||
@property
|
||||
def inc(self):
|
||||
"""Get the inc portion of this :class:`Timestamp`.
|
||||
"""
|
||||
return self.__inc
|
||||
|
||||
def __eq__(self, other):
|
||||
if isinstance(other, Timestamp):
|
||||
return (self.__time == other.time and self.__inc == other.inc)
|
||||
else:
|
||||
return NotImplemented
|
||||
|
||||
def __hash__(self):
|
||||
return hash(self.time) ^ hash(self.inc)
|
||||
|
||||
def __ne__(self, other):
|
||||
return not self == other
|
||||
|
||||
def __lt__(self, other):
|
||||
if isinstance(other, Timestamp):
|
||||
return (self.time, self.inc) < (other.time, other.inc)
|
||||
return NotImplemented
|
||||
|
||||
def __le__(self, other):
|
||||
if isinstance(other, Timestamp):
|
||||
return (self.time, self.inc) <= (other.time, other.inc)
|
||||
return NotImplemented
|
||||
|
||||
def __gt__(self, other):
|
||||
if isinstance(other, Timestamp):
|
||||
return (self.time, self.inc) > (other.time, other.inc)
|
||||
return NotImplemented
|
||||
|
||||
def __ge__(self, other):
|
||||
if isinstance(other, Timestamp):
|
||||
return (self.time, self.inc) >= (other.time, other.inc)
|
||||
return NotImplemented
|
||||
|
||||
def __repr__(self):
|
||||
return "Timestamp(%s, %s)" % (self.__time, self.__inc)
|
||||
|
||||
def as_datetime(self):
|
||||
"""Return a :class:`~datetime.datetime` instance corresponding
|
||||
to the time portion of this :class:`Timestamp`.
|
||||
|
||||
The returned datetime's timezone is UTC.
|
||||
"""
|
||||
return datetime.datetime.fromtimestamp(self.__time, utc)
|
||||
52
venv/lib/python3.8/site-packages/bson/tz_util.py
Normal file
52
venv/lib/python3.8/site-packages/bson/tz_util.py
Normal file
@@ -0,0 +1,52 @@
|
||||
# Copyright 2010-2015 MongoDB, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Timezone related utilities for BSON."""
|
||||
|
||||
from datetime import (timedelta,
|
||||
tzinfo)
|
||||
|
||||
ZERO = timedelta(0)
|
||||
|
||||
|
||||
class FixedOffset(tzinfo):
|
||||
"""Fixed offset timezone, in minutes east from UTC.
|
||||
|
||||
Implementation based from the Python `standard library documentation
|
||||
<http://docs.python.org/library/datetime.html#tzinfo-objects>`_.
|
||||
Defining __getinitargs__ enables pickling / copying.
|
||||
"""
|
||||
|
||||
def __init__(self, offset, name):
|
||||
if isinstance(offset, timedelta):
|
||||
self.__offset = offset
|
||||
else:
|
||||
self.__offset = timedelta(minutes=offset)
|
||||
self.__name = name
|
||||
|
||||
def __getinitargs__(self):
|
||||
return self.__offset, self.__name
|
||||
|
||||
def utcoffset(self, dt):
|
||||
return self.__offset
|
||||
|
||||
def tzname(self, dt):
|
||||
return self.__name
|
||||
|
||||
def dst(self, dt):
|
||||
return ZERO
|
||||
|
||||
|
||||
utc = FixedOffset(0, "UTC")
|
||||
"""Fixed offset timezone representing UTC."""
|
||||
Reference in New Issue
Block a user