PYTHON-3605 Move type annotations to parameter list in rendered docs (#1441)
This commit is contained in:
parent
51f7fe29f6
commit
6537415da7
@ -172,6 +172,8 @@ request](https://help.github.com/articles/using-pull-requests). You
|
||||
might also use the GitHub
|
||||
[Edit](https://github.com/blog/844-forking-with-the-edit-button) button.
|
||||
|
||||
We use the [Sphinx docstring format](https://sphinx-rtd-tutorial.readthedocs.io/en/latest/docstrings.html).
|
||||
|
||||
You can build the documentation locally by running:
|
||||
|
||||
```bash
|
||||
|
||||
@ -1026,12 +1026,11 @@ def encode(
|
||||
:class:`~bson.errors.InvalidDocument` if `document` cannot be
|
||||
converted to :class:`BSON`.
|
||||
|
||||
:Parameters:
|
||||
- `document`: mapping type representing a document
|
||||
- `check_keys` (optional): check if keys start with '$' or
|
||||
:param document: mapping type representing a document
|
||||
:param check_keys: check if keys start with '$' or
|
||||
contain '.', raising :class:`~bson.errors.InvalidDocument` in
|
||||
either case
|
||||
- `codec_options` (optional): An instance of
|
||||
:param codec_options: An instance of
|
||||
:class:`~bson.codec_options.CodecOptions`.
|
||||
|
||||
.. versionadded:: 3.9
|
||||
@ -1072,10 +1071,9 @@ def decode(
|
||||
>>> type(decoded_doc)
|
||||
<class 'collections.OrderedDict'>
|
||||
|
||||
:Parameters:
|
||||
- `data`: the BSON to decode. Any bytes-like object that implements
|
||||
:param data: the BSON to decode. Any bytes-like object that implements
|
||||
the buffer protocol.
|
||||
- `codec_options` (optional): An instance of
|
||||
:param codec_options: An instance of
|
||||
:class:`~bson.codec_options.CodecOptions`.
|
||||
|
||||
.. versionadded:: 3.9
|
||||
@ -1141,9 +1139,8 @@ def decode_all(
|
||||
`data` must be a bytes-like object implementing the buffer protocol that
|
||||
provides concatenated, valid, BSON-encoded documents.
|
||||
|
||||
:Parameters:
|
||||
- `data`: BSON data
|
||||
- `codec_options` (optional): An instance of
|
||||
:param data: BSON data
|
||||
:param codec_options: An instance of
|
||||
:class:`~bson.codec_options.CodecOptions`.
|
||||
|
||||
.. versionchanged:: 3.9
|
||||
@ -1238,20 +1235,18 @@ def _decode_all_selective(
|
||||
|
||||
`data` must be a string representing a valid, BSON-encoded document.
|
||||
|
||||
:Parameters:
|
||||
- `data`: BSON data
|
||||
- `codec_options`: An instance of
|
||||
:param data: BSON data
|
||||
:param codec_options: An instance of
|
||||
:class:`~bson.codec_options.CodecOptions` with user-specified type
|
||||
decoders. If no decoders are found, this method is the same as
|
||||
``decode_all``.
|
||||
- `fields`: Map of document namespaces where data that needs
|
||||
:param fields: Map of document namespaces where data that needs
|
||||
to be custom decoded lives or None. For example, to custom decode a
|
||||
list of objects in 'field1.subfield1', the specified value should be
|
||||
``{'field1': {'subfield1': 1}}``. If ``fields`` is an empty map or
|
||||
None, this method is the same as ``decode_all``.
|
||||
|
||||
:Returns:
|
||||
- `document_list`: Single-member list containing the decoded document.
|
||||
:return: Single-member list containing the decoded document.
|
||||
|
||||
.. versionadded:: 3.8
|
||||
"""
|
||||
@ -1298,9 +1293,8 @@ def decode_iter(
|
||||
`data` must be a string of concatenated, valid, BSON-encoded
|
||||
documents.
|
||||
|
||||
:Parameters:
|
||||
- `data`: BSON data
|
||||
- `codec_options` (optional): An instance of
|
||||
:param data: BSON data
|
||||
:param codec_options: An instance of
|
||||
:class:`~bson.codec_options.CodecOptions`.
|
||||
|
||||
.. versionchanged:: 3.0
|
||||
@ -1346,9 +1340,8 @@ def decode_file_iter(
|
||||
Works similarly to the decode_all function, but reads from the file object
|
||||
in chunks and parses bson in chunks, yielding one document at a time.
|
||||
|
||||
:Parameters:
|
||||
- `file_obj`: A file object containing BSON data.
|
||||
- `codec_options` (optional): An instance of
|
||||
:param file_obj: A file object containing BSON data.
|
||||
:param codec_options: An instance of
|
||||
:class:`~bson.codec_options.CodecOptions`.
|
||||
|
||||
.. versionchanged:: 3.0
|
||||
@ -1377,8 +1370,7 @@ def is_valid(bson: bytes) -> bool:
|
||||
:class:`bytes`. Returns ``True``
|
||||
if `bson` is valid :class:`BSON`, ``False`` otherwise.
|
||||
|
||||
:Parameters:
|
||||
- `bson`: the data to be validated
|
||||
:param bson: the data to be validated
|
||||
"""
|
||||
if not isinstance(bson, bytes):
|
||||
raise TypeError("BSON data must be an instance of a subclass of bytes")
|
||||
@ -1414,12 +1406,11 @@ class BSON(bytes):
|
||||
:class:`str'. Raises :class:`~bson.errors.InvalidDocument`
|
||||
if `document` cannot be converted to :class:`BSON`.
|
||||
|
||||
:Parameters:
|
||||
- `document`: mapping type representing a document
|
||||
- `check_keys` (optional): check if keys start with '$' or
|
||||
:param document: mapping type representing a document
|
||||
:param check_keys: check if keys start with '$' or
|
||||
contain '.', raising :class:`~bson.errors.InvalidDocument` in
|
||||
either case
|
||||
- `codec_options` (optional): An instance of
|
||||
:param codec_options: An instance of
|
||||
:class:`~bson.codec_options.CodecOptions`.
|
||||
|
||||
.. versionchanged:: 3.0
|
||||
@ -1447,8 +1438,7 @@ class BSON(bytes):
|
||||
>>> type(decoded_doc)
|
||||
<class 'collections.OrderedDict'>
|
||||
|
||||
:Parameters:
|
||||
- `codec_options` (optional): An instance of
|
||||
:param codec_options: An instance of
|
||||
:class:`~bson.codec_options.CodecOptions`.
|
||||
|
||||
.. versionchanged:: 3.0
|
||||
|
||||
@ -211,10 +211,9 @@ class Binary(bytes):
|
||||
.. note::
|
||||
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
|
||||
:param data: the binary data to represent. Can be any bytes-like type
|
||||
that implements the buffer protocol.
|
||||
- `subtype` (optional): the `binary subtype
|
||||
:param subtype: the `binary subtype
|
||||
<https://bsonspec.org/spec.html>`_
|
||||
to use
|
||||
|
||||
@ -253,9 +252,8 @@ class Binary(bytes):
|
||||
Raises :exc:`TypeError` if `uuid` is not an instance of
|
||||
:class:`~uuid.UUID`.
|
||||
|
||||
:Parameters:
|
||||
- `uuid`: A :class:`uuid.UUID` instance.
|
||||
- `uuid_representation`: A member of
|
||||
:param uuid: A :class:`uuid.UUID` instance.
|
||||
:param uuid_representation: A member of
|
||||
:class:`~bson.binary.UuidRepresentation`. Default:
|
||||
:const:`~bson.binary.UuidRepresentation.STANDARD`.
|
||||
See :ref:`handling-uuid-data-example` for details.
|
||||
@ -304,8 +302,7 @@ class Binary(bytes):
|
||||
Raises :exc:`ValueError` if this :class:`~bson.binary.Binary` instance
|
||||
does not contain a UUID.
|
||||
|
||||
:Parameters:
|
||||
- `uuid_representation`: A member of
|
||||
:param uuid_representation: A member of
|
||||
:class:`~bson.binary.UuidRepresentation`. Default:
|
||||
:const:`~bson.binary.UuidRepresentation.STANDARD`.
|
||||
See :ref:`handling-uuid-data-example` for details.
|
||||
|
||||
@ -31,15 +31,14 @@ class Code(str):
|
||||
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
|
||||
:param 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
|
||||
:param scope: 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
|
||||
:param kwargs: scope variables can also be passed as
|
||||
keyword arguments. These are applied after `scope` and `code`.
|
||||
|
||||
.. versionchanged:: 3.4
|
||||
|
||||
@ -120,14 +120,13 @@ class TypeRegistry:
|
||||
|
||||
See :ref:`custom-type-type-registry` documentation for an example.
|
||||
|
||||
:Parameters:
|
||||
- `type_codecs` (optional): iterable of type codec instances. If
|
||||
:param type_codecs: 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,
|
||||
:param fallback_encoder: 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.
|
||||
@ -324,30 +323,29 @@ else:
|
||||
See :doc:`/examples/uuid` for examples using the `uuid_representation`
|
||||
option.
|
||||
|
||||
:Parameters:
|
||||
- `document_class`: BSON documents returned in queries will be decoded
|
||||
:param document_class: BSON documents returned in queries will be decoded
|
||||
to an instance of this class. Must be a subclass of
|
||||
:class:`~collections.abc.MutableMapping`. Defaults to :class:`dict`.
|
||||
- `tz_aware`: If ``True``, BSON datetimes will be decoded to timezone
|
||||
:param 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
|
||||
:param uuid_representation: The BSON representation to use when encoding
|
||||
and decoding instances of :class:`~uuid.UUID`. Defaults to
|
||||
:data:`~bson.binary.UuidRepresentation.UNSPECIFIED`. New
|
||||
applications should consider setting this to
|
||||
:data:`~bson.binary.UuidRepresentation.STANDARD` for cross language
|
||||
compatibility. See :ref:`handling-uuid-data-example` for details.
|
||||
- `unicode_decode_error_handler`: The error handler to apply when
|
||||
:param 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', 'backslashreplace', 'surrogateescape', and
|
||||
'ignore'. Defaults to 'strict'.
|
||||
- `tzinfo`: A :class:`~datetime.tzinfo` subclass that specifies the
|
||||
:param 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
|
||||
:param type_registry: Instance of :class:`TypeRegistry` used to customize
|
||||
encoding and decoding behavior.
|
||||
- `datetime_conversion`: Specifies how UTC datetimes should be decoded
|
||||
:param datetime_conversion: Specifies how UTC datetimes should be decoded
|
||||
within BSON. Valid options include 'datetime_ms' to return as a
|
||||
DatetimeMS, 'datetime' to return as a datetime.datetime and
|
||||
raising a ValueError for out-of-range values, 'datetime_auto' to
|
||||
|
||||
@ -55,8 +55,7 @@ class DatetimeMS:
|
||||
'datetime_auto'. See :ref:`handling-out-of-range-datetimes` for
|
||||
details.
|
||||
|
||||
:Parameters:
|
||||
- `value`: An instance of :class:`datetime.datetime` to be
|
||||
:param value: An instance of :class:`datetime.datetime` to be
|
||||
represented as milliseconds since the Unix epoch, or int of
|
||||
milliseconds since the Unix epoch.
|
||||
"""
|
||||
@ -104,8 +103,7 @@ class DatetimeMS:
|
||||
) -> datetime.datetime:
|
||||
"""Create a Python :class:`~datetime.datetime` from this DatetimeMS object.
|
||||
|
||||
:Parameters:
|
||||
- `codec_options`: A CodecOptions instance for specifying how the
|
||||
:param codec_options: A CodecOptions instance for specifying how the
|
||||
resulting DatetimeMS object will be formatted using ``tz_aware``
|
||||
and ``tz_info``. Defaults to
|
||||
:const:`~bson.codec_options.DEFAULT_CODEC_OPTIONS`.
|
||||
|
||||
@ -47,11 +47,10 @@ class DBRef:
|
||||
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
|
||||
:param collection: name of the collection the document is stored in
|
||||
:param id: the value of the document's ``"_id"`` field
|
||||
:param database: name of the database to reference
|
||||
:param kwargs: additional keyword arguments will
|
||||
create additional, custom fields
|
||||
|
||||
.. seealso:: The MongoDB documentation on `dbrefs <https://dochub.mongodb.org/core/dbrefs>`_.
|
||||
|
||||
@ -70,8 +70,7 @@ def create_decimal128_context() -> decimal.Context:
|
||||
def _decimal_to_128(value: _VALUE_OPTIONS) -> Tuple[int, int]:
|
||||
"""Converts a decimal.Decimal to BID (high bits, low bits).
|
||||
|
||||
:Parameters:
|
||||
- `value`: An instance of decimal.Decimal
|
||||
:param value: An instance of decimal.Decimal
|
||||
"""
|
||||
with decimal.localcontext(_DEC128_CTX) as ctx:
|
||||
value = ctx.create_decimal(value)
|
||||
@ -126,8 +125,7 @@ class Decimal128:
|
||||
>>> Decimal128((3474527112516337664, 5))
|
||||
Decimal128('0.0005')
|
||||
|
||||
:Parameters:
|
||||
- `value`: An instance of :class:`decimal.Decimal`, string, or tuple of
|
||||
:param 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`
|
||||
@ -275,8 +273,7 @@ class Decimal128:
|
||||
"""Create an instance of :class:`Decimal128` from Binary Integer
|
||||
Decimal string.
|
||||
|
||||
:Parameters:
|
||||
- `value`: 16 byte string (128-bit IEEE 754-2008 decimal floating
|
||||
:param value: 16 byte string (128-bit IEEE 754-2008 decimal floating
|
||||
point in Binary Integer Decimal (BID) format).
|
||||
"""
|
||||
if not isinstance(value, bytes):
|
||||
|
||||
@ -25,8 +25,7 @@ class Int64(int):
|
||||
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
|
||||
:param value: the numeric value to represent
|
||||
"""
|
||||
|
||||
__slots__ = ()
|
||||
|
||||
@ -246,33 +246,32 @@ class JSONOptions(_BASE_CLASS):
|
||||
def __init__(self, *args: Any, **kwargs: Any):
|
||||
"""Encapsulates JSON options for :func:`dumps` and :func:`loads`.
|
||||
|
||||
:Parameters:
|
||||
- `strict_number_long`: If ``True``, :class:`~bson.int64.Int64` objects
|
||||
:param 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
|
||||
:param 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
|
||||
:param 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
|
||||
:param 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
|
||||
:param 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 :class:`~bson.binary.UuidRepresentation`
|
||||
:param uuid_representation: The :class:`~bson.binary.UuidRepresentation`
|
||||
to use when encoding and decoding instances of :class:`uuid.UUID`.
|
||||
Defaults to :const:`~bson.binary.UuidRepresentation.UNSPECIFIED`.
|
||||
- `tz_aware`: If ``True``, MongoDB Extended JSON's *Strict mode* type
|
||||
:param 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 ``False``.
|
||||
- `tzinfo`: A :class:`datetime.tzinfo` subclass that specifies the
|
||||
:param 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`.
|
||||
- `datetime_conversion`: Specifies how UTC datetimes should be decoded
|
||||
:param datetime_conversion: Specifies how UTC datetimes should be decoded
|
||||
within BSON. Valid options include 'datetime_ms' to return as a
|
||||
DatetimeMS, 'datetime' to return as a datetime.datetime and
|
||||
raising a ValueError for out-of-range values, 'datetime_auto' to
|
||||
@ -280,8 +279,8 @@ class JSONOptions(_BASE_CLASS):
|
||||
out-of-range and 'datetime_clamp' to clamp to the minimum and
|
||||
maximum possible datetimes. Defaults to 'datetime'. See
|
||||
:ref:`handling-out-of-range-datetimes` for details.
|
||||
- `args`: arguments to :class:`~bson.codec_options.CodecOptions`
|
||||
- `kwargs`: arguments to :class:`~bson.codec_options.CodecOptions`
|
||||
:param args: arguments to :class:`~bson.codec_options.CodecOptions`
|
||||
:param kwargs: arguments to :class:`~bson.codec_options.CodecOptions`
|
||||
|
||||
.. seealso:: The specification for Relaxed and Canonical `Extended JSON`_.
|
||||
|
||||
@ -456,8 +455,7 @@ def dumps(obj: Any, *args: Any, **kwargs: Any) -> str:
|
||||
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
|
||||
:param json_options: A :class:`JSONOptions` instance used to modify the
|
||||
encoding of MongoDB Extended JSON types. Defaults to
|
||||
:const:`DEFAULT_JSON_OPTIONS`.
|
||||
|
||||
@ -480,8 +478,7 @@ def loads(s: Union[str, bytes, bytearray], *args: Any, **kwargs: Any) -> Any:
|
||||
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
|
||||
:param json_options: A :class:`JSONOptions` instance used to modify the
|
||||
decoding of MongoDB Extended JSON types. Defaults to
|
||||
:const:`DEFAULT_JSON_OPTIONS`.
|
||||
|
||||
|
||||
@ -84,8 +84,7 @@ class ObjectId:
|
||||
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.
|
||||
:param oid: a valid ObjectId.
|
||||
|
||||
.. seealso:: The MongoDB documentation on `ObjectIds <http://dochub.mongodb.org/core/objectids>`_.
|
||||
|
||||
@ -126,8 +125,7 @@ class ObjectId:
|
||||
>>> dummy_id = ObjectId.from_datetime(gen_time)
|
||||
>>> result = collection.find({"_id": {"$lt": dummy_id}})
|
||||
|
||||
:Parameters:
|
||||
- `generation_time`: :class:`~datetime.datetime` to be used
|
||||
:param generation_time: :class:`~datetime.datetime` to be used
|
||||
as the generation time for the resulting ObjectId.
|
||||
"""
|
||||
offset = generation_time.utcoffset()
|
||||
@ -141,8 +139,7 @@ class ObjectId:
|
||||
def is_valid(cls: Type[ObjectId], oid: Any) -> bool:
|
||||
"""Checks if a `oid` string is valid or not.
|
||||
|
||||
:Parameters:
|
||||
- `oid`: the object id to validate
|
||||
:param oid: the object id to validate
|
||||
|
||||
.. versionadded:: 2.3
|
||||
"""
|
||||
@ -186,8 +183,7 @@ class ObjectId:
|
||||
:class:`bytes`, or ObjectId. Raises InvalidId if it is not a
|
||||
valid ObjectId.
|
||||
|
||||
:Parameters:
|
||||
- `oid`: a valid ObjectId
|
||||
:param oid: a valid ObjectId
|
||||
"""
|
||||
if isinstance(oid, ObjectId):
|
||||
self.__id = oid.binary
|
||||
|
||||
@ -65,9 +65,8 @@ def _inflate_bson(
|
||||
) -> MutableMapping[str, Any]:
|
||||
"""Inflates the top level fields of a BSON document.
|
||||
|
||||
:Parameters:
|
||||
- `bson_bytes`: the BSON bytes that compose this document
|
||||
- `codec_options`: An instance of
|
||||
:param bson_bytes: the BSON bytes that compose this document
|
||||
:param codec_options: An instance of
|
||||
:class:`~bson.codec_options.CodecOptions` whose ``document_class``
|
||||
must be :class:`RawBSONDocument`.
|
||||
"""
|
||||
@ -110,9 +109,8 @@ class RawBSONDocument(Mapping[str, Any]):
|
||||
>>> raw_doc['_id']
|
||||
'my_doc'
|
||||
|
||||
:Parameters:
|
||||
- `bson_bytes`: the BSON bytes that compose this document
|
||||
- `codec_options` (optional): An instance of
|
||||
:param bson_bytes: the BSON bytes that compose this document
|
||||
:param codec_options: An instance of
|
||||
:class:`~bson.codec_options.CodecOptions` whose ``document_class``
|
||||
must be :class:`RawBSONDocument`. The default is
|
||||
:attr:`DEFAULT_RAW_BSON_OPTIONS`.
|
||||
|
||||
@ -66,8 +66,7 @@ class Regex(Generic[_T]):
|
||||
>>> regex.flags ^= re.UNICODE
|
||||
>>> db.collection.insert_one({'pattern': regex})
|
||||
|
||||
:Parameters:
|
||||
- `regex`: A regular expression object from ``re.compile()``.
|
||||
:param regex: A regular expression object from ``re.compile()``.
|
||||
|
||||
.. warning::
|
||||
Python regular expressions use a different syntax and different
|
||||
@ -89,9 +88,8 @@ class Regex(Generic[_T]):
|
||||
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
|
||||
:param pattern: string
|
||||
:param flags: an integer bitmask, or a string of flag
|
||||
characters like "im" for IGNORECASE and MULTILINE
|
||||
"""
|
||||
if not isinstance(pattern, (str, bytes)):
|
||||
|
||||
@ -47,11 +47,10 @@ class Timestamp:
|
||||
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
|
||||
:param time: time in seconds since epoch UTC, or a naive UTC
|
||||
:class:`~datetime.datetime`, or an aware
|
||||
:class:`~datetime.datetime`
|
||||
- `inc`: the incrementing counter
|
||||
:param inc: the incrementing counter
|
||||
"""
|
||||
if isinstance(time, datetime.datetime):
|
||||
offset = time.utcoffset()
|
||||
|
||||
@ -94,6 +94,8 @@ linkcheck_ignore = [
|
||||
# -- Options for extensions ----------------------------------------------------
|
||||
autoclass_content = "init"
|
||||
|
||||
autodoc_typehints = "description"
|
||||
|
||||
doctest_path = [Path("..").resolve()]
|
||||
|
||||
doctest_test_doctest_blocks = ""
|
||||
|
||||
@ -63,9 +63,8 @@ class GridFS:
|
||||
Raises :class:`TypeError` if `database` is not an instance of
|
||||
:class:`~pymongo.database.Database`.
|
||||
|
||||
:Parameters:
|
||||
- `database`: database to use
|
||||
- `collection` (optional): root collection to use
|
||||
:param database: database to use
|
||||
:param collection: root collection to use
|
||||
|
||||
.. versionchanged:: 4.0
|
||||
Removed the `disable_md5` parameter. See
|
||||
@ -110,8 +109,7 @@ class GridFS:
|
||||
not already exist in GridFS. Otherwise
|
||||
:class:`~gridfs.errors.FileExists` is raised.
|
||||
|
||||
:Parameters:
|
||||
- `**kwargs` (optional): keyword arguments for file creation
|
||||
:param kwargs: keyword arguments for file creation
|
||||
"""
|
||||
return GridIn(self.__collection, **kwargs)
|
||||
|
||||
@ -135,9 +133,8 @@ class GridFS:
|
||||
not already exist in GridFS. Otherwise
|
||||
:class:`~gridfs.errors.FileExists` is raised.
|
||||
|
||||
:Parameters:
|
||||
- `data`: data to be written as a file.
|
||||
- `**kwargs` (optional): keyword arguments for file creation
|
||||
:param data: data to be written as a file.
|
||||
:param kwargs: keyword arguments for file creation
|
||||
|
||||
.. versionchanged:: 3.0
|
||||
w=0 writes to GridFS are now prohibited.
|
||||
@ -152,9 +149,8 @@ class GridFS:
|
||||
Returns an instance of :class:`~gridfs.grid_file.GridOut`,
|
||||
which provides a file-like interface for reading.
|
||||
|
||||
:Parameters:
|
||||
- `file_id`: ``"_id"`` of the file to get
|
||||
- `session` (optional): a
|
||||
:param file_id: ``"_id"`` of the file to get
|
||||
:param session: a
|
||||
:class:`~pymongo.client_session.ClientSession`
|
||||
|
||||
.. versionchanged:: 3.6
|
||||
@ -193,13 +189,12 @@ class GridFS:
|
||||
Raises :class:`~gridfs.errors.NoFile` if no such version of
|
||||
that file exists.
|
||||
|
||||
:Parameters:
|
||||
- `filename`: ``"filename"`` of the file to get, or `None`
|
||||
- `version` (optional): version of the file to get (defaults
|
||||
:param filename: ``"filename"`` of the file to get, or `None`
|
||||
:param version: version of the file to get (defaults
|
||||
to -1, the most recent version uploaded)
|
||||
- `session` (optional): a
|
||||
:param session: a
|
||||
:class:`~pymongo.client_session.ClientSession`
|
||||
- `**kwargs` (optional): find files by custom metadata.
|
||||
:param kwargs: find files by custom metadata.
|
||||
|
||||
.. versionchanged:: 3.6
|
||||
Added ``session`` parameter.
|
||||
@ -235,11 +230,10 @@ class GridFS:
|
||||
Equivalent to calling :meth:`get_version` with the default
|
||||
`version` (``-1``).
|
||||
|
||||
:Parameters:
|
||||
- `filename`: ``"filename"`` of the file to get, or `None`
|
||||
- `session` (optional): a
|
||||
:param filename: ``"filename"`` of the file to get, or `None`
|
||||
:param session: a
|
||||
:class:`~pymongo.client_session.ClientSession`
|
||||
- `**kwargs` (optional): find files by custom metadata.
|
||||
:param kwargs: find files by custom metadata.
|
||||
|
||||
.. versionchanged:: 3.6
|
||||
Added ``session`` parameter.
|
||||
@ -261,9 +255,8 @@ class GridFS:
|
||||
.. note:: Deletes of non-existent files are considered successful
|
||||
since the end result is the same: no file with that _id remains.
|
||||
|
||||
:Parameters:
|
||||
- `file_id`: ``"_id"`` of the file to delete
|
||||
- `session` (optional): a
|
||||
:param file_id: ``"_id"`` of the file to delete
|
||||
:param session: a
|
||||
:class:`~pymongo.client_session.ClientSession`
|
||||
|
||||
.. versionchanged:: 3.6
|
||||
@ -280,8 +273,7 @@ class GridFS:
|
||||
"""List the names of all files stored in this instance of
|
||||
:class:`GridFS`.
|
||||
|
||||
:Parameters:
|
||||
- `session` (optional): a
|
||||
:param session: a
|
||||
:class:`~pymongo.client_session.ClientSession`
|
||||
|
||||
.. versionchanged:: 3.6
|
||||
@ -309,19 +301,20 @@ class GridFS:
|
||||
All arguments to :meth:`find` are also valid arguments for
|
||||
:meth:`find_one`, although any `limit` argument will be
|
||||
ignored. Returns a single :class:`~gridfs.grid_file.GridOut`,
|
||||
or ``None`` if no matching file is found. For example::
|
||||
or ``None`` if no matching file is found. For example:
|
||||
|
||||
.. code-block: python
|
||||
|
||||
file = fs.find_one({"filename": "lisa.txt"})
|
||||
|
||||
:Parameters:
|
||||
- `filter` (optional): a dictionary specifying
|
||||
:param filter: a dictionary specifying
|
||||
the query to be performing OR any other type to be used as
|
||||
the value for a query for ``"_id"`` in the file collection.
|
||||
- `*args` (optional): any additional positional arguments are
|
||||
:param args: any additional positional arguments are
|
||||
the same as the arguments to :meth:`find`.
|
||||
- `session` (optional): a
|
||||
:param session: a
|
||||
:class:`~pymongo.client_session.ClientSession`
|
||||
- `**kwargs` (optional): any additional keyword arguments
|
||||
:param kwargs: any additional keyword arguments
|
||||
are the same as the arguments to :meth:`find`.
|
||||
|
||||
.. versionchanged:: 3.6
|
||||
@ -367,20 +360,19 @@ class GridFS:
|
||||
:meth:`find`, all returned :class:`~gridfs.grid_file.GridOut` instances
|
||||
are associated with that session.
|
||||
|
||||
:Parameters:
|
||||
- `filter` (optional): A query document that selects which files
|
||||
:param filter: A query document that selects which files
|
||||
to include in the result set. Can be an empty document to include
|
||||
all files.
|
||||
- `skip` (optional): the number of files to omit (from
|
||||
:param skip: the number of files to omit (from
|
||||
the start of the result set) when returning the results
|
||||
- `limit` (optional): the maximum number of results to
|
||||
:param limit: the maximum number of results to
|
||||
return
|
||||
- `no_cursor_timeout` (optional): if False (the default), any
|
||||
:param no_cursor_timeout: if False (the default), any
|
||||
returned cursor is closed by the server after 10 minutes of
|
||||
inactivity. If set to True, the returned cursor will never
|
||||
time out on the server. Care should be taken to ensure that
|
||||
cursors with no_cursor_timeout turned on are properly closed.
|
||||
- `sort` (optional): a list of (key, direction) pairs
|
||||
:param sort: a list of (key, direction) pairs
|
||||
specifying the sort order for this query. See
|
||||
:meth:`~pymongo.cursor.Cursor.sort` for details.
|
||||
|
||||
@ -429,12 +421,11 @@ class GridFS:
|
||||
create appropriate indexes; application developers should be
|
||||
sure to create indexes if needed and as appropriate.
|
||||
|
||||
:Parameters:
|
||||
- `document_or_id` (optional): query document, or _id of the
|
||||
:param document_or_id: query document, or _id of the
|
||||
document to check for
|
||||
- `session` (optional): a
|
||||
:param session: a
|
||||
:class:`~pymongo.client_session.ClientSession`
|
||||
- `**kwargs` (optional): keyword arguments are used as a
|
||||
:param kwargs: keyword arguments are used as a
|
||||
query document, if they're present.
|
||||
|
||||
.. versionchanged:: 3.6
|
||||
@ -468,15 +459,14 @@ class GridFSBucket:
|
||||
Raises :exc:`~pymongo.errors.ConfigurationError` if `write_concern`
|
||||
is not acknowledged.
|
||||
|
||||
:Parameters:
|
||||
- `database`: database to use.
|
||||
- `bucket_name` (optional): The name of the bucket. Defaults to 'fs'.
|
||||
- `chunk_size_bytes` (optional): The chunk size in bytes. Defaults
|
||||
:param database: database to use.
|
||||
:param bucket_name: The name of the bucket. Defaults to 'fs'.
|
||||
:param chunk_size_bytes: The chunk size in bytes. Defaults
|
||||
to 255KB.
|
||||
- `write_concern` (optional): The
|
||||
:param write_concern: The
|
||||
:class:`~pymongo.write_concern.WriteConcern` to use. If ``None``
|
||||
(the default) db.write_concern is used.
|
||||
- `read_preference` (optional): The read preference to use. If
|
||||
:param read_preference: The read preference to use. If
|
||||
``None`` (the default) db.read_preference is used.
|
||||
|
||||
.. versionchanged:: 4.0
|
||||
@ -545,14 +535,13 @@ class GridFSBucket:
|
||||
that file exists.
|
||||
Raises :exc:`~ValueError` if `filename` is not a string.
|
||||
|
||||
:Parameters:
|
||||
- `filename`: The name of the file to upload.
|
||||
- `chunk_size_bytes` (options): The number of bytes per chunk of this
|
||||
:param filename: The name of the file to upload.
|
||||
:param chunk_size_bytes` (options): The number of bytes per chunk of this
|
||||
file. Defaults to the chunk_size_bytes in :class:`GridFSBucket`.
|
||||
- `metadata` (optional): User data for the 'metadata' field of the
|
||||
:param metadata: User data for the 'metadata' field of the
|
||||
files collection document. If not provided the metadata field will
|
||||
be omitted from the files collection document.
|
||||
- `session` (optional): a
|
||||
:param session: a
|
||||
:class:`~pymongo.client_session.ClientSession`
|
||||
|
||||
.. versionchanged:: 3.6
|
||||
@ -603,16 +592,15 @@ class GridFSBucket:
|
||||
that file exists.
|
||||
Raises :exc:`~ValueError` if `filename` is not a string.
|
||||
|
||||
:Parameters:
|
||||
- `file_id`: The id to use for this file. The id must not have
|
||||
:param file_id: The id to use for this file. The id must not have
|
||||
already been used for another file.
|
||||
- `filename`: The name of the file to upload.
|
||||
- `chunk_size_bytes` (options): The number of bytes per chunk of this
|
||||
:param filename: The name of the file to upload.
|
||||
:param chunk_size_bytes` (options): The number of bytes per chunk of this
|
||||
file. Defaults to the chunk_size_bytes in :class:`GridFSBucket`.
|
||||
- `metadata` (optional): User data for the 'metadata' field of the
|
||||
:param metadata: User data for the 'metadata' field of the
|
||||
files collection document. If not provided the metadata field will
|
||||
be omitted from the files collection document.
|
||||
- `session` (optional): a
|
||||
:param session: a
|
||||
:class:`~pymongo.client_session.ClientSession`
|
||||
|
||||
.. versionchanged:: 3.6
|
||||
@ -661,16 +649,15 @@ class GridFSBucket:
|
||||
that file exists.
|
||||
Raises :exc:`~ValueError` if `filename` is not a string.
|
||||
|
||||
:Parameters:
|
||||
- `filename`: The name of the file to upload.
|
||||
- `source`: The source stream of the content to be uploaded. Must be
|
||||
:param filename: The name of the file to upload.
|
||||
:param source: The source stream of the content to be uploaded. Must be
|
||||
a file-like object that implements :meth:`read` or a string.
|
||||
- `chunk_size_bytes` (options): The number of bytes per chunk of this
|
||||
:param chunk_size_bytes` (options): The number of bytes per chunk of this
|
||||
file. Defaults to the chunk_size_bytes of :class:`GridFSBucket`.
|
||||
- `metadata` (optional): User data for the 'metadata' field of the
|
||||
:param metadata: User data for the 'metadata' field of the
|
||||
files collection document. If not provided the metadata field will
|
||||
be omitted from the files collection document.
|
||||
- `session` (optional): a
|
||||
:param session: a
|
||||
:class:`~pymongo.client_session.ClientSession`
|
||||
|
||||
.. versionchanged:: 3.6
|
||||
@ -710,18 +697,17 @@ class GridFSBucket:
|
||||
that file exists.
|
||||
Raises :exc:`~ValueError` if `filename` is not a string.
|
||||
|
||||
:Parameters:
|
||||
- `file_id`: The id to use for this file. The id must not have
|
||||
:param file_id: The id to use for this file. The id must not have
|
||||
already been used for another file.
|
||||
- `filename`: The name of the file to upload.
|
||||
- `source`: The source stream of the content to be uploaded. Must be
|
||||
:param filename: The name of the file to upload.
|
||||
:param source: The source stream of the content to be uploaded. Must be
|
||||
a file-like object that implements :meth:`read` or a string.
|
||||
- `chunk_size_bytes` (options): The number of bytes per chunk of this
|
||||
:param chunk_size_bytes` (options): The number of bytes per chunk of this
|
||||
file. Defaults to the chunk_size_bytes of :class:`GridFSBucket`.
|
||||
- `metadata` (optional): User data for the 'metadata' field of the
|
||||
:param metadata: User data for the 'metadata' field of the
|
||||
files collection document. If not provided the metadata field will
|
||||
be omitted from the files collection document.
|
||||
- `session` (optional): a
|
||||
:param session: a
|
||||
:class:`~pymongo.client_session.ClientSession`
|
||||
|
||||
.. versionchanged:: 3.6
|
||||
@ -751,9 +737,8 @@ class GridFSBucket:
|
||||
|
||||
Raises :exc:`~gridfs.errors.NoFile` if no file with file_id exists.
|
||||
|
||||
:Parameters:
|
||||
- `file_id`: The _id of the file to be downloaded.
|
||||
- `session` (optional): a
|
||||
:param file_id: The _id of the file to be downloaded.
|
||||
:param session: a
|
||||
:class:`~pymongo.client_session.ClientSession`
|
||||
|
||||
.. versionchanged:: 3.6
|
||||
@ -786,10 +771,9 @@ class GridFSBucket:
|
||||
|
||||
Raises :exc:`~gridfs.errors.NoFile` if no file with file_id exists.
|
||||
|
||||
:Parameters:
|
||||
- `file_id`: The _id of the file to be downloaded.
|
||||
- `destination`: a file-like object implementing :meth:`write`.
|
||||
- `session` (optional): a
|
||||
:param file_id: The _id of the file to be downloaded.
|
||||
:param destination: a file-like object implementing :meth:`write`.
|
||||
:param session: a
|
||||
:class:`~pymongo.client_session.ClientSession`
|
||||
|
||||
.. versionchanged:: 3.6
|
||||
@ -817,9 +801,8 @@ class GridFSBucket:
|
||||
|
||||
Raises :exc:`~gridfs.errors.NoFile` if no file with file_id exists.
|
||||
|
||||
:Parameters:
|
||||
- `file_id`: The _id of the file to be deleted.
|
||||
- `session` (optional): a
|
||||
:param file_id: The _id of the file to be deleted.
|
||||
:param session: a
|
||||
:class:`~pymongo.client_session.ClientSession`
|
||||
|
||||
.. versionchanged:: 3.6
|
||||
@ -864,17 +847,16 @@ class GridFSBucket:
|
||||
:meth:`find`, all returned :class:`~gridfs.grid_file.GridOut` instances
|
||||
are associated with that session.
|
||||
|
||||
:Parameters:
|
||||
- `filter`: Search query.
|
||||
- `batch_size` (optional): The number of documents to return per
|
||||
:param filter: Search query.
|
||||
:param batch_size: The number of documents to return per
|
||||
batch.
|
||||
- `limit` (optional): The maximum number of documents to return.
|
||||
- `no_cursor_timeout` (optional): The server normally times out idle
|
||||
:param limit: The maximum number of documents to return.
|
||||
:param no_cursor_timeout: The server normally times out idle
|
||||
cursors after an inactivity period (10 minutes) to prevent excess
|
||||
memory use. Set this option to True prevent that.
|
||||
- `skip` (optional): The number of documents to skip before
|
||||
:param skip: The number of documents to skip before
|
||||
returning.
|
||||
- `sort` (optional): The order by which to sort results. Defaults to
|
||||
:param sort: The order by which to sort results. Defaults to
|
||||
None.
|
||||
"""
|
||||
return GridOutCursor(self._collection, *args, **kwargs)
|
||||
@ -899,12 +881,11 @@ class GridFSBucket:
|
||||
|
||||
Raises :exc:`~ValueError` filename is not a string.
|
||||
|
||||
:Parameters:
|
||||
- `filename`: The name of the file to read from.
|
||||
- `revision` (optional): Which revision (documents with the same
|
||||
:param filename: The name of the file to read from.
|
||||
:param revision: Which revision (documents with the same
|
||||
filename and different uploadDate) of the file to retrieve.
|
||||
Defaults to -1 (the most recent revision).
|
||||
- `session` (optional): a
|
||||
:param session: a
|
||||
:class:`~pymongo.client_session.ClientSession`
|
||||
|
||||
:Note: Revision numbers are defined as follows:
|
||||
@ -958,13 +939,12 @@ class GridFSBucket:
|
||||
|
||||
Raises :exc:`~ValueError` if `filename` is not a string.
|
||||
|
||||
:Parameters:
|
||||
- `filename`: The name of the file to read from.
|
||||
- `destination`: A file-like object that implements :meth:`write`.
|
||||
- `revision` (optional): Which revision (documents with the same
|
||||
:param filename: The name of the file to read from.
|
||||
:param destination: A file-like object that implements :meth:`write`.
|
||||
:param revision: Which revision (documents with the same
|
||||
filename and different uploadDate) of the file to retrieve.
|
||||
Defaults to -1 (the most recent revision).
|
||||
- `session` (optional): a
|
||||
:param session: a
|
||||
:class:`~pymongo.client_session.ClientSession`
|
||||
|
||||
:Note: Revision numbers are defined as follows:
|
||||
@ -1001,10 +981,9 @@ class GridFSBucket:
|
||||
|
||||
Raises :exc:`~gridfs.errors.NoFile` if no file with file_id exists.
|
||||
|
||||
:Parameters:
|
||||
- `file_id`: The _id of the file to be renamed.
|
||||
- `new_filename`: The new name of the file.
|
||||
- `session` (optional): a
|
||||
:param file_id: The _id of the file to be renamed.
|
||||
:param new_filename: The new name of the file.
|
||||
:param session: a
|
||||
:class:`~pymongo.client_session.ClientSession`
|
||||
|
||||
.. versionchanged:: 3.6
|
||||
|
||||
@ -152,12 +152,11 @@ class GridIn:
|
||||
- ``"encoding"``: encoding used for this file. Any :class:`str`
|
||||
that is written to the file will be converted to :class:`bytes`.
|
||||
|
||||
:Parameters:
|
||||
- `root_collection`: root collection to write to
|
||||
- `session` (optional): a
|
||||
:param root_collection: root collection to write to
|
||||
:param session: a
|
||||
:class:`~pymongo.client_session.ClientSession` to use for all
|
||||
commands
|
||||
- `**kwargs: Any` (optional): file level options (see above)
|
||||
:param kwargs: Any: file level options (see above)
|
||||
|
||||
.. versionchanged:: 4.0
|
||||
Removed the `disable_md5` parameter. See
|
||||
@ -344,8 +343,7 @@ class GridIn:
|
||||
Unicode data is only allowed if the file has an :attr:`encoding`
|
||||
attribute.
|
||||
|
||||
:Parameters:
|
||||
- `data`: string of bytes or file-like object to be written
|
||||
:param data: string of bytes or file-like object to be written
|
||||
to the file
|
||||
"""
|
||||
if self._closed:
|
||||
@ -438,12 +436,11 @@ class GridOut(io.IOBase):
|
||||
:class:`TypeError` if `root_collection` is not an instance of
|
||||
:class:`~pymongo.collection.Collection`.
|
||||
|
||||
:Parameters:
|
||||
- `root_collection`: root collection to read from
|
||||
- `file_id` (optional): value of ``"_id"`` for the file to read
|
||||
- `file_document` (optional): file document from
|
||||
:param root_collection: root collection to read from
|
||||
:param file_id: value of ``"_id"`` for the file to read
|
||||
:param file_document: file document from
|
||||
`root_collection.files`
|
||||
- `session` (optional): a
|
||||
:param session: a
|
||||
:class:`~pymongo.client_session.ClientSession` to use for all
|
||||
commands
|
||||
|
||||
@ -608,8 +605,7 @@ class GridOut(io.IOBase):
|
||||
The bytes are returned as an instance of :class:`bytes`
|
||||
If `size` is negative or omitted all data is read.
|
||||
|
||||
:Parameters:
|
||||
- `size` (optional): the number of bytes to read
|
||||
:param size: the number of bytes to read
|
||||
|
||||
.. versionchanged:: 3.8
|
||||
This method now only checks for extra chunks after reading the
|
||||
@ -621,8 +617,7 @@ class GridOut(io.IOBase):
|
||||
def readline(self, size: int = -1) -> bytes: # type: ignore[override]
|
||||
"""Read one line or up to `size` bytes from the file.
|
||||
|
||||
:Parameters:
|
||||
- `size` (optional): the maximum number of bytes to read
|
||||
:param size: the maximum number of bytes to read
|
||||
"""
|
||||
return self._read_size_or_line(size=size, line=True)
|
||||
|
||||
@ -633,10 +628,9 @@ class GridOut(io.IOBase):
|
||||
def seek(self, pos: int, whence: int = _SEEK_SET) -> int:
|
||||
"""Set the current position of this file.
|
||||
|
||||
:Parameters:
|
||||
- `pos`: the position (or offset if using relative
|
||||
:param pos: the position (or offset if using relative
|
||||
positioning) to seek to
|
||||
- `whence` (optional): where to seek
|
||||
:param whence: where to seek
|
||||
from. :attr:`os.SEEK_SET` (``0``) for absolute file
|
||||
positioning, :attr:`os.SEEK_CUR` (``1``) to seek relative
|
||||
to the current position, :attr:`os.SEEK_END` (``2``) to
|
||||
|
||||
@ -159,11 +159,9 @@ def timeout(seconds: Optional[float]) -> ContextManager[None]:
|
||||
coll.find_one() # Still uses the original 5 second deadline.
|
||||
coll.find_one() # Uses the original 5 second deadline.
|
||||
|
||||
:Parameters:
|
||||
- `seconds`: A non-negative floating point number expressing seconds, or None.
|
||||
:param seconds: A non-negative floating point number expressing seconds, or None.
|
||||
|
||||
:Raises:
|
||||
- :py:class:`ValueError`: When `seconds` is negative.
|
||||
:raises: :py:class:`ValueError`: When `seconds` is negative.
|
||||
|
||||
See :ref:`timeout-example` for more examples.
|
||||
|
||||
|
||||
@ -89,18 +89,16 @@ class _Run:
|
||||
def index(self, idx: int) -> int:
|
||||
"""Get the original index of an operation in this run.
|
||||
|
||||
:Parameters:
|
||||
- `idx`: The Run index that maps to the original index.
|
||||
:param idx: The Run index that maps to the original index.
|
||||
"""
|
||||
return self.index_map[idx]
|
||||
|
||||
def add(self, original_index: int, operation: Any) -> None:
|
||||
"""Add an operation to this Run instance.
|
||||
|
||||
:Parameters:
|
||||
- `original_index`: The original index of this operation
|
||||
:param original_index: The original index of this operation
|
||||
within a larger bulk operation.
|
||||
- `operation`: The operation document.
|
||||
:param operation: The operation document.
|
||||
"""
|
||||
self.index_map.append(original_index)
|
||||
self.ops.append(operation)
|
||||
|
||||
@ -356,8 +356,7 @@ class ChangeStream(Generic[_DocumentType]):
|
||||
document is returned, otherwise, if the getMore returns no documents
|
||||
(because there have been no changes) then ``None`` is returned.
|
||||
|
||||
:Returns:
|
||||
The next change document or ``None`` when no document is available
|
||||
:return: The next change document or ``None`` when no document is available
|
||||
after running a single getMore or when the cursor is closed.
|
||||
|
||||
.. versionadded:: 3.8
|
||||
|
||||
@ -183,13 +183,12 @@ if TYPE_CHECKING:
|
||||
class SessionOptions:
|
||||
"""Options for a new :class:`ClientSession`.
|
||||
|
||||
:Parameters:
|
||||
- `causal_consistency` (optional): If True, read operations are causally
|
||||
:param causal_consistency: If True, read operations are causally
|
||||
ordered within the session. Defaults to True when the ``snapshot``
|
||||
option is ``False``.
|
||||
- `default_transaction_options` (optional): The default
|
||||
:param default_transaction_options: The default
|
||||
TransactionOptions to use for transactions started on this session.
|
||||
- `snapshot` (optional): If True, then all reads performed using this
|
||||
:param snapshot: If True, then all reads performed using this
|
||||
session will read from the same snapshot. This option is incompatible
|
||||
with ``causal_consistency=True``. Defaults to ``False``.
|
||||
|
||||
@ -247,21 +246,20 @@ class SessionOptions:
|
||||
class TransactionOptions:
|
||||
"""Options for :meth:`ClientSession.start_transaction`.
|
||||
|
||||
:Parameters:
|
||||
- `read_concern` (optional): The
|
||||
:param read_concern: The
|
||||
:class:`~pymongo.read_concern.ReadConcern` to use for this transaction.
|
||||
If ``None`` (the default) the :attr:`read_preference` of
|
||||
the :class:`MongoClient` is used.
|
||||
- `write_concern` (optional): The
|
||||
:param write_concern: The
|
||||
:class:`~pymongo.write_concern.WriteConcern` to use for this
|
||||
transaction. If ``None`` (the default) the :attr:`read_preference` of
|
||||
the :class:`MongoClient` is used.
|
||||
- `read_preference` (optional): The read preference to use. If
|
||||
:param read_preference: The read preference to use. If
|
||||
``None`` (the default) the :attr:`read_preference` of this
|
||||
:class:`MongoClient` is used. See :mod:`~pymongo.read_preferences`
|
||||
for options. Transactions which read must use
|
||||
:attr:`~pymongo.read_preferences.ReadPreference.PRIMARY`.
|
||||
- `max_commit_time_ms` (optional): The maximum amount of time to allow a
|
||||
:param max_commit_time_ms: The maximum amount of time to allow a
|
||||
single commitTransaction command to run. This option is an alias for
|
||||
maxTimeMS option on the commitTransaction command. If ``None`` (the
|
||||
default) maxTimeMS is not used.
|
||||
@ -655,24 +653,22 @@ class ClientSession:
|
||||
timeout is reached will be re-raised. Applications that desire a
|
||||
different timeout duration should not use this method.
|
||||
|
||||
:Parameters:
|
||||
- `callback`: The callable ``callback`` to run inside a transaction.
|
||||
:param callback: The callable ``callback`` to run inside a transaction.
|
||||
The callable must accept a single argument, this session. Note,
|
||||
under certain error conditions the callback may be run multiple
|
||||
times.
|
||||
- `read_concern` (optional): The
|
||||
:param read_concern: The
|
||||
:class:`~pymongo.read_concern.ReadConcern` to use for this
|
||||
transaction.
|
||||
- `write_concern` (optional): The
|
||||
:param write_concern: The
|
||||
:class:`~pymongo.write_concern.WriteConcern` to use for this
|
||||
transaction.
|
||||
- `read_preference` (optional): The read preference to use for this
|
||||
:param read_preference: The read preference to use for this
|
||||
transaction. If ``None`` (the default) the :attr:`read_preference`
|
||||
of this :class:`Database` is used. See
|
||||
:mod:`~pymongo.read_preferences` for options.
|
||||
|
||||
:Returns:
|
||||
The return value of the ``callback``.
|
||||
:return: The return value of the ``callback``.
|
||||
|
||||
.. versionadded:: 3.9
|
||||
"""
|
||||
@ -833,8 +829,7 @@ class ClientSession:
|
||||
def _finish_transaction_with_retry(self, command_name: str) -> dict[str, Any]:
|
||||
"""Run commit or abort with one retry after any retryable error.
|
||||
|
||||
:Parameters:
|
||||
- `command_name`: Either "commitTransaction" or "abortTransaction".
|
||||
:param command_name: Either "commitTransaction" or "abortTransaction".
|
||||
"""
|
||||
|
||||
def func(
|
||||
@ -882,8 +877,7 @@ class ClientSession:
|
||||
def advance_cluster_time(self, cluster_time: Mapping[str, Any]) -> None:
|
||||
"""Update the cluster time for this session.
|
||||
|
||||
:Parameters:
|
||||
- `cluster_time`: The
|
||||
:param cluster_time: The
|
||||
:data:`~pymongo.client_session.ClientSession.cluster_time` from
|
||||
another `ClientSession` instance.
|
||||
"""
|
||||
@ -904,8 +898,7 @@ class ClientSession:
|
||||
def advance_operation_time(self, operation_time: Timestamp) -> None:
|
||||
"""Update the operation time for this session.
|
||||
|
||||
:Parameters:
|
||||
- `operation_time`: The
|
||||
:param operation_time: The
|
||||
:data:`~pymongo.client_session.ClientSession.operation_time` from
|
||||
another `ClientSession` instance.
|
||||
"""
|
||||
|
||||
@ -97,22 +97,21 @@ class CollationCaseFirst:
|
||||
class Collation:
|
||||
"""Collation
|
||||
|
||||
:Parameters:
|
||||
- `locale`: (string) The locale of the collation. This should be a string
|
||||
:param locale: (string) The locale of the collation. This should be a string
|
||||
that identifies an `ICU locale ID` exactly. For example, ``en_US`` is
|
||||
valid, but ``en_us`` and ``en-US`` are not. Consult the MongoDB
|
||||
documentation for a list of supported locales.
|
||||
- `caseLevel`: (optional) If ``True``, turn on case sensitivity if
|
||||
:param caseLevel: (optional) If ``True``, turn on case sensitivity if
|
||||
`strength` is 1 or 2 (case sensitivity is implied if `strength` is
|
||||
greater than 2). Defaults to ``False``.
|
||||
- `caseFirst`: (optional) Specify that either uppercase or lowercase
|
||||
:param caseFirst: (optional) Specify that either uppercase or lowercase
|
||||
characters take precedence. Must be one of the following values:
|
||||
|
||||
* :data:`~CollationCaseFirst.UPPER`
|
||||
* :data:`~CollationCaseFirst.LOWER`
|
||||
* :data:`~CollationCaseFirst.OFF` (the default)
|
||||
|
||||
- `strength`: (optional) Specify the comparison strength. This is also
|
||||
:param strength: Specify the comparison strength. This is also
|
||||
known as the ICU comparison level. This must be one of the following
|
||||
values:
|
||||
|
||||
@ -126,27 +125,27 @@ class Collation:
|
||||
`strength` of :data:`~CollationStrength.SECONDARY` differentiates
|
||||
characters based both on the unadorned base character and its accents.
|
||||
|
||||
- `numericOrdering`: (optional) If ``True``, order numbers numerically
|
||||
:param numericOrdering: If ``True``, order numbers numerically
|
||||
instead of in collation order (defaults to ``False``).
|
||||
- `alternate`: (optional) Specify whether spaces and punctuation are
|
||||
:param alternate: Specify whether spaces and punctuation are
|
||||
considered base characters. This must be one of the following values:
|
||||
|
||||
* :data:`~CollationAlternate.NON_IGNORABLE` (the default)
|
||||
* :data:`~CollationAlternate.SHIFTED`
|
||||
|
||||
- `maxVariable`: (optional) When `alternate` is
|
||||
:param maxVariable: When `alternate` is
|
||||
:data:`~CollationAlternate.SHIFTED`, this option specifies what
|
||||
characters may be ignored. This must be one of the following values:
|
||||
|
||||
* :data:`~CollationMaxVariable.PUNCT` (the default)
|
||||
* :data:`~CollationMaxVariable.SPACE`
|
||||
|
||||
- `normalization`: (optional) If ``True``, normalizes text into Unicode
|
||||
:param normalization: If ``True``, normalizes text into Unicode
|
||||
NFD. Defaults to ``False``.
|
||||
- `backwards`: (optional) If ``True``, accents on characters are
|
||||
:param backwards: If ``True``, accents on characters are
|
||||
considered from the back of the word to the front, as it is done in some
|
||||
French dictionary ordering traditions. Defaults to ``False``.
|
||||
- `kwargs`: (optional) Keyword arguments supplying any additional options
|
||||
:param kwargs: Keyword arguments supplying any additional options
|
||||
to be sent with this Collation object.
|
||||
|
||||
.. versionadded: 3.4
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -134,8 +134,7 @@ class CommandCursor(Generic[_DocumentType]):
|
||||
Raises :exc:`TypeError` if `batch_size` is not an integer.
|
||||
Raises :exc:`ValueError` if `batch_size` is less than ``0``.
|
||||
|
||||
:Parameters:
|
||||
- `batch_size`: The size of each batch of results requested.
|
||||
:param batch_size: The size of each batch of results requested.
|
||||
"""
|
||||
if not isinstance(batch_size, int):
|
||||
raise TypeError("batch_size must be an integer")
|
||||
@ -335,8 +334,7 @@ class CommandCursor(Generic[_DocumentType]):
|
||||
document is returned, otherwise, if the getMore returns no documents
|
||||
(because there is no additional data) then ``None`` is returned.
|
||||
|
||||
:Returns:
|
||||
The next document or ``None`` when no document is available
|
||||
:return: The next document or ``None`` when no document is available
|
||||
after running a single getMore or when the cursor is closed.
|
||||
|
||||
.. versionadded:: 4.5
|
||||
|
||||
@ -828,9 +828,8 @@ def get_validated_options(
|
||||
"""Validate each entry in options and raise a warning if it is not valid.
|
||||
Returns a copy of options with invalid entries removed.
|
||||
|
||||
:Parameters:
|
||||
- `opts`: A dict containing MongoDB URI options.
|
||||
- `warn` (optional): If ``True`` then warnings will be logged and
|
||||
:param opts: A dict containing MongoDB URI options.
|
||||
:param warn: If ``True`` then warnings will be logged and
|
||||
invalid options will be ignored. Otherwise, invalid options will
|
||||
cause errors.
|
||||
"""
|
||||
|
||||
@ -548,8 +548,7 @@ class Cursor(Generic[_DocumentType]):
|
||||
|
||||
.. note:: `allow_disk_use` requires server version **>= 4.4**
|
||||
|
||||
:Parameters:
|
||||
- `allow_disk_use`: if True, MongoDB may use temporary
|
||||
:param allow_disk_use: if True, MongoDB may use temporary
|
||||
disk files to store data exceeding the system memory limit while
|
||||
processing a blocking sort operation.
|
||||
|
||||
@ -570,8 +569,7 @@ class Cursor(Generic[_DocumentType]):
|
||||
has already been used. The last `limit` applied to this cursor
|
||||
takes precedence. A limit of ``0`` is equivalent to no limit.
|
||||
|
||||
:Parameters:
|
||||
- `limit`: the number of results to return
|
||||
:param limit: the number of results to return
|
||||
|
||||
.. seealso:: The MongoDB documentation on `limit <https://dochub.mongodb.org/core/limit>`_.
|
||||
"""
|
||||
@ -601,8 +599,7 @@ class Cursor(Generic[_DocumentType]):
|
||||
:class:`Cursor` has already been used. The last `batch_size`
|
||||
applied to this cursor takes precedence.
|
||||
|
||||
:Parameters:
|
||||
- `batch_size`: The size of each batch of results requested.
|
||||
:param batch_size: The size of each batch of results requested.
|
||||
"""
|
||||
if not isinstance(batch_size, int):
|
||||
raise TypeError("batch_size must be an integer")
|
||||
@ -622,8 +619,7 @@ class Cursor(Generic[_DocumentType]):
|
||||
already been used. The last `skip` applied to this cursor takes
|
||||
precedence.
|
||||
|
||||
:Parameters:
|
||||
- `skip`: the number of results to skip
|
||||
:param skip: the number of results to skip
|
||||
"""
|
||||
if not isinstance(skip, int):
|
||||
raise TypeError("skip must be an integer")
|
||||
@ -644,8 +640,7 @@ class Cursor(Generic[_DocumentType]):
|
||||
Raises :exc:`~pymongo.errors.InvalidOperation` if this :class:`Cursor`
|
||||
has already been used.
|
||||
|
||||
:Parameters:
|
||||
- `max_time_ms`: the time limit after which the operation is aborted
|
||||
:param max_time_ms: the time limit after which the operation is aborted
|
||||
"""
|
||||
if not isinstance(max_time_ms, int) and max_time_ms is not None:
|
||||
raise TypeError("max_time_ms must be an integer or None")
|
||||
@ -665,8 +660,7 @@ class Cursor(Generic[_DocumentType]):
|
||||
|
||||
.. note:: `max_await_time_ms` requires server version **>= 3.2**
|
||||
|
||||
:Parameters:
|
||||
- `max_await_time_ms`: the time limit after which the operation is
|
||||
:param max_await_time_ms: the time limit after which the operation is
|
||||
aborted
|
||||
|
||||
.. versionadded:: 3.2
|
||||
@ -727,8 +721,7 @@ class Cursor(Generic[_DocumentType]):
|
||||
start value, or a stop value less than or equal to the start
|
||||
value.
|
||||
|
||||
:Parameters:
|
||||
- `index`: An integer or slice index to be applied to this cursor
|
||||
:param index: An integer or slice index to be applied to this cursor
|
||||
"""
|
||||
self.__check_okay_to_chain()
|
||||
self.__empty = False
|
||||
@ -777,8 +770,7 @@ class Cursor(Generic[_DocumentType]):
|
||||
cursor has already been used. Only the last :meth:`max_scan`
|
||||
applied to this cursor has any effect.
|
||||
|
||||
:Parameters:
|
||||
- `max_scan`: the maximum number of documents to scan
|
||||
:param max_scan: the maximum number of documents to scan
|
||||
|
||||
.. versionchanged:: 3.7
|
||||
Deprecated :meth:`max_scan`. Support for this option is deprecated in
|
||||
@ -796,8 +788,7 @@ class Cursor(Generic[_DocumentType]):
|
||||
the query uses the expected index and starting in MongoDB 4.2
|
||||
:meth:`~hint` will be required.
|
||||
|
||||
:Parameters:
|
||||
- `spec`: a list of field, limit pairs specifying the exclusive
|
||||
:param spec: a list of field, limit pairs specifying the exclusive
|
||||
upper bound for all keys of a specific index in order.
|
||||
|
||||
.. versionchanged:: 3.8
|
||||
@ -819,8 +810,7 @@ class Cursor(Generic[_DocumentType]):
|
||||
the query uses the expected index and starting in MongoDB 4.2
|
||||
:meth:`~hint` will be required.
|
||||
|
||||
:Parameters:
|
||||
- `spec`: a list of field, limit pairs specifying the inclusive
|
||||
:param spec: a list of field, limit pairs specifying the inclusive
|
||||
lower bound for all keys of a specific index in order.
|
||||
|
||||
.. versionchanged:: 3.8
|
||||
@ -873,10 +863,9 @@ class Cursor(Generic[_DocumentType]):
|
||||
already been used. Only the last :meth:`sort` applied to this
|
||||
cursor has any effect.
|
||||
|
||||
:Parameters:
|
||||
- `key_or_list`: a single key or a list of (key, direction)
|
||||
:param key_or_list: a single key or a list of (key, direction)
|
||||
pairs specifying the keys to sort on
|
||||
- `direction` (optional): only used if `key_or_list` is a single
|
||||
:param direction: only used if `key_or_list` is a single
|
||||
key, if not given :data:`~pymongo.ASCENDING` is assumed
|
||||
"""
|
||||
self.__check_okay_to_chain()
|
||||
@ -896,8 +885,7 @@ class Cursor(Generic[_DocumentType]):
|
||||
:class:`~pymongo.collection.Collection` instance on which
|
||||
:meth:`~pymongo.collection.Collection.find` was called.
|
||||
|
||||
:Parameters:
|
||||
- `key`: name of key for which we want to get the distinct values
|
||||
:param key: name of key for which we want to get the distinct values
|
||||
|
||||
.. seealso:: :meth:`pymongo.collection.Collection.distinct`
|
||||
"""
|
||||
@ -961,8 +949,7 @@ class Cursor(Generic[_DocumentType]):
|
||||
cleared. The last hint applied to this cursor takes precedence
|
||||
over all others.
|
||||
|
||||
:Parameters:
|
||||
- `index`: index to hint on (as an index specifier)
|
||||
:param index: index to hint on (as an index specifier)
|
||||
"""
|
||||
self.__check_okay_to_chain()
|
||||
self.__set_hint(index)
|
||||
@ -973,8 +960,7 @@ class Cursor(Generic[_DocumentType]):
|
||||
|
||||
http://mongodb.com/docs/manual/reference/operator/comment/
|
||||
|
||||
:Parameters:
|
||||
- `comment`: A string to attach to the query to help interpret and
|
||||
:param comment: A string to attach to the query to help interpret and
|
||||
trace the operation in the server logs and in profile data.
|
||||
|
||||
.. versionadded:: 2.7
|
||||
@ -1005,8 +991,7 @@ class Cursor(Generic[_DocumentType]):
|
||||
.. note:: MongoDB 4.4 drops support for :class:`~bson.code.Code`
|
||||
with scope variables. Consider using `$expr`_ instead.
|
||||
|
||||
:Parameters:
|
||||
- `code`: JavaScript expression to use as a filter
|
||||
:param code: JavaScript expression to use as a filter
|
||||
|
||||
.. _$expr: https://mongodb.com/docs/manual/reference/operator/query/expr/
|
||||
.. _$where: https://mongodb.com/docs/manual/reference/operator/query/where/
|
||||
@ -1035,8 +1020,7 @@ class Cursor(Generic[_DocumentType]):
|
||||
already been used. Only the last collation applied to this cursor has
|
||||
any effect.
|
||||
|
||||
:Parameters:
|
||||
- `collation`: An instance of :class:`~pymongo.collation.Collation`.
|
||||
:param collation: An instance of :class:`~pymongo.collation.Collation`.
|
||||
"""
|
||||
self.__check_okay_to_chain()
|
||||
self.__collation = validate_collation_or_none(collation)
|
||||
|
||||
@ -87,18 +87,17 @@ class Database(common.BaseObject, Generic[_DocumentType]):
|
||||
:class:`str`. Raises :class:`~pymongo.errors.InvalidName` if
|
||||
`name` is not a valid database name.
|
||||
|
||||
:Parameters:
|
||||
- `client`: A :class:`~pymongo.mongo_client.MongoClient` instance.
|
||||
- `name`: The database name.
|
||||
- `codec_options` (optional): An instance of
|
||||
:param client: A :class:`~pymongo.mongo_client.MongoClient` instance.
|
||||
:param name: The database name.
|
||||
:param codec_options: An instance of
|
||||
:class:`~bson.codec_options.CodecOptions`. If ``None`` (the
|
||||
default) client.codec_options is used.
|
||||
- `read_preference` (optional): The read preference to use. If
|
||||
:param read_preference: The read preference to use. If
|
||||
``None`` (the default) client.read_preference is used.
|
||||
- `write_concern` (optional): An instance of
|
||||
:param write_concern: An instance of
|
||||
:class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
|
||||
default) client.write_concern is used.
|
||||
- `read_concern` (optional): An instance of
|
||||
:param read_concern: An instance of
|
||||
:class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the
|
||||
default) client.read_concern is used.
|
||||
|
||||
@ -171,20 +170,19 @@ class Database(common.BaseObject, Generic[_DocumentType]):
|
||||
>>> db2.read_preference
|
||||
Secondary(tag_sets=[{'node': 'analytics'}], max_staleness=-1, hedge=None)
|
||||
|
||||
:Parameters:
|
||||
- `codec_options` (optional): An instance of
|
||||
:param codec_options: An instance of
|
||||
:class:`~bson.codec_options.CodecOptions`. If ``None`` (the
|
||||
default) the :attr:`codec_options` of this :class:`Collection`
|
||||
is used.
|
||||
- `read_preference` (optional): The read preference to use. If
|
||||
:param read_preference: The read preference to use. If
|
||||
``None`` (the default) the :attr:`read_preference` of this
|
||||
:class:`Collection` is used. See :mod:`~pymongo.read_preferences`
|
||||
for options.
|
||||
- `write_concern` (optional): An instance of
|
||||
:param write_concern: An instance of
|
||||
:class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
|
||||
default) the :attr:`write_concern` of this :class:`Collection`
|
||||
is used.
|
||||
- `read_concern` (optional): An instance of
|
||||
:param read_concern: An instance of
|
||||
:class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the
|
||||
default) the :attr:`read_concern` of this :class:`Collection`
|
||||
is used.
|
||||
@ -219,8 +217,7 @@ class Database(common.BaseObject, Generic[_DocumentType]):
|
||||
|
||||
Raises InvalidName if an invalid collection name is used.
|
||||
|
||||
:Parameters:
|
||||
- `name`: the name of the collection to get
|
||||
:param name: the name of the collection to get
|
||||
"""
|
||||
if name.startswith("_"):
|
||||
raise AttributeError(
|
||||
@ -234,8 +231,7 @@ class Database(common.BaseObject, Generic[_DocumentType]):
|
||||
|
||||
Raises InvalidName if an invalid collection name is used.
|
||||
|
||||
:Parameters:
|
||||
- `name`: the name of the collection to get
|
||||
:param name: the name of the collection to get
|
||||
"""
|
||||
return Collection(self, name)
|
||||
|
||||
@ -265,21 +261,20 @@ class Database(common.BaseObject, Generic[_DocumentType]):
|
||||
>>> coll2.read_preference
|
||||
Secondary(tag_sets=None)
|
||||
|
||||
:Parameters:
|
||||
- `name`: The name of the collection - a string.
|
||||
- `codec_options` (optional): An instance of
|
||||
:param name: The name of the collection - a string.
|
||||
:param codec_options: An instance of
|
||||
:class:`~bson.codec_options.CodecOptions`. If ``None`` (the
|
||||
default) the :attr:`codec_options` of this :class:`Database` is
|
||||
used.
|
||||
- `read_preference` (optional): The read preference to use. If
|
||||
:param read_preference: The read preference to use. If
|
||||
``None`` (the default) the :attr:`read_preference` of this
|
||||
:class:`Database` is used. See :mod:`~pymongo.read_preferences`
|
||||
for options.
|
||||
- `write_concern` (optional): An instance of
|
||||
:param write_concern: An instance of
|
||||
:class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
|
||||
default) the :attr:`write_concern` of this :class:`Database` is
|
||||
used.
|
||||
- `read_concern` (optional): An instance of
|
||||
:param read_concern: An instance of
|
||||
:class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the
|
||||
default) the :attr:`read_concern` of this :class:`Database` is
|
||||
used.
|
||||
@ -341,30 +336,29 @@ class Database(common.BaseObject, Generic[_DocumentType]):
|
||||
creation. :class:`~pymongo.errors.CollectionInvalid` will be
|
||||
raised if the collection already exists.
|
||||
|
||||
:Parameters:
|
||||
- `name`: the name of the collection to create
|
||||
- `codec_options` (optional): An instance of
|
||||
:param name: the name of the collection to create
|
||||
:param codec_options: An instance of
|
||||
:class:`~bson.codec_options.CodecOptions`. If ``None`` (the
|
||||
default) the :attr:`codec_options` of this :class:`Database` is
|
||||
used.
|
||||
- `read_preference` (optional): The read preference to use. If
|
||||
:param read_preference: The read preference to use. If
|
||||
``None`` (the default) the :attr:`read_preference` of this
|
||||
:class:`Database` is used.
|
||||
- `write_concern` (optional): An instance of
|
||||
:param write_concern: An instance of
|
||||
:class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
|
||||
default) the :attr:`write_concern` of this :class:`Database` is
|
||||
used.
|
||||
- `read_concern` (optional): An instance of
|
||||
:param read_concern: An instance of
|
||||
:class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the
|
||||
default) the :attr:`read_concern` of this :class:`Database` is
|
||||
used.
|
||||
- `collation` (optional): An instance of
|
||||
:param collation: An instance of
|
||||
:class:`~pymongo.collation.Collation`.
|
||||
- `session` (optional): a
|
||||
:param session: a
|
||||
:class:`~pymongo.client_session.ClientSession`.
|
||||
- ``check_exists`` (optional): if True (the default), send a listCollections command to
|
||||
:param `check_exists`: if True (the default), send a listCollections command to
|
||||
check if the collection already exists before creation.
|
||||
- `**kwargs` (optional): additional keyword arguments will
|
||||
:param kwargs: additional keyword arguments will
|
||||
be passed as options for the `create collection command`_
|
||||
|
||||
All optional `create collection command`_ parameters should be passed
|
||||
@ -503,11 +497,10 @@ class Database(common.BaseObject, Generic[_DocumentType]):
|
||||
.. note:: The :attr:`~pymongo.database.Database.write_concern` of
|
||||
this collection is automatically applied to this operation.
|
||||
|
||||
:Parameters:
|
||||
- `pipeline`: a list of aggregation pipeline stages
|
||||
- `session` (optional): a
|
||||
:param pipeline: a list of aggregation pipeline stages
|
||||
:param session: a
|
||||
:class:`~pymongo.client_session.ClientSession`.
|
||||
- `**kwargs` (optional): extra `aggregate command`_ parameters.
|
||||
:param kwargs: extra `aggregate command`_ parameters.
|
||||
|
||||
All optional `aggregate command`_ parameters should be passed as
|
||||
keyword arguments to this method. Valid options include, but are not
|
||||
@ -529,8 +522,7 @@ class Database(common.BaseObject, Generic[_DocumentType]):
|
||||
aggregate expression context (e.g. ``"$$var"``). This option is
|
||||
only supported on MongoDB >= 5.0.
|
||||
|
||||
:Returns:
|
||||
A :class:`~pymongo.command_cursor.CommandCursor` over the result
|
||||
:return: A :class:`~pymongo.command_cursor.CommandCursor` over the result
|
||||
set.
|
||||
|
||||
.. versionadded:: 3.9
|
||||
@ -610,47 +602,45 @@ class Database(common.BaseObject, Generic[_DocumentType]):
|
||||
For a precise description of the resume process see the
|
||||
`change streams specification`_.
|
||||
|
||||
:Parameters:
|
||||
- `pipeline` (optional): A list of aggregation pipeline stages to
|
||||
:param pipeline: A list of aggregation pipeline stages to
|
||||
append to an initial ``$changeStream`` stage. Not all
|
||||
pipeline stages are valid after a ``$changeStream`` stage, see the
|
||||
MongoDB documentation on change streams for the supported stages.
|
||||
- `full_document` (optional): The fullDocument to pass as an option
|
||||
:param full_document: The fullDocument to pass as an option
|
||||
to the ``$changeStream`` stage. Allowed values: 'updateLookup',
|
||||
'whenAvailable', 'required'. When set to 'updateLookup', the
|
||||
change notification for partial updates will include both a delta
|
||||
describing the changes to the document, as well as a copy of the
|
||||
entire document that was changed from some time after the change
|
||||
occurred.
|
||||
- `full_document_before_change`: Allowed values: 'whenAvailable'
|
||||
:param full_document_before_change: Allowed values: 'whenAvailable'
|
||||
and 'required'. Change events may now result in a
|
||||
'fullDocumentBeforeChange' response field.
|
||||
- `resume_after` (optional): A resume token. If provided, the
|
||||
:param resume_after: A resume token. If provided, the
|
||||
change stream will start returning changes that occur directly
|
||||
after the operation specified in the resume token. A resume token
|
||||
is the _id value of a change document.
|
||||
- `max_await_time_ms` (optional): The maximum time in milliseconds
|
||||
:param max_await_time_ms: The maximum time in milliseconds
|
||||
for the server to wait for changes before responding to a getMore
|
||||
operation.
|
||||
- `batch_size` (optional): The maximum number of documents to return
|
||||
:param batch_size: The maximum number of documents to return
|
||||
per batch.
|
||||
- `collation` (optional): The :class:`~pymongo.collation.Collation`
|
||||
:param collation: The :class:`~pymongo.collation.Collation`
|
||||
to use for the aggregation.
|
||||
- `start_at_operation_time` (optional): If provided, the resulting
|
||||
:param start_at_operation_time: If provided, the resulting
|
||||
change stream will only return changes that occurred at or after
|
||||
the specified :class:`~bson.timestamp.Timestamp`. Requires
|
||||
MongoDB >= 4.0.
|
||||
- `session` (optional): a
|
||||
:param session: a
|
||||
:class:`~pymongo.client_session.ClientSession`.
|
||||
- `start_after` (optional): The same as `resume_after` except that
|
||||
:param start_after: The same as `resume_after` except that
|
||||
`start_after` can resume notifications after an invalidate event.
|
||||
This option and `resume_after` are mutually exclusive.
|
||||
- `comment` (optional): A user-provided comment to attach to this
|
||||
:param comment: A user-provided comment to attach to this
|
||||
command.
|
||||
- `show_expanded_events` (optional): Include expanded events such as DDL events like `dropIndexes`.
|
||||
:param show_expanded_events: Include expanded events such as DDL events like `dropIndexes`.
|
||||
|
||||
:Returns:
|
||||
A :class:`~pymongo.change_stream.DatabaseChangeStream` cursor.
|
||||
:return: A :class:`~pymongo.change_stream.DatabaseChangeStream` cursor.
|
||||
|
||||
.. versionchanged:: 4.3
|
||||
Added `show_expanded_events` parameter.
|
||||
@ -825,8 +815,7 @@ class Database(common.BaseObject, Generic[_DocumentType]):
|
||||
|
||||
>>> db.command("filemd5", object_id, root=file_root)
|
||||
|
||||
:Parameters:
|
||||
- `command`: document representing the command to be issued,
|
||||
:param command: document representing the command to be issued,
|
||||
or the name of the command (for simple commands only).
|
||||
|
||||
.. note:: the order of keys in the `command` document is
|
||||
@ -835,25 +824,25 @@ class Database(common.BaseObject, Generic[_DocumentType]):
|
||||
should use an instance of :class:`~bson.son.SON` or
|
||||
a string and kwargs instead of a Python `dict`.
|
||||
|
||||
- `value` (optional): value to use for the command verb when
|
||||
:param value: value to use for the command verb when
|
||||
`command` is passed as a string
|
||||
- `check` (optional): check the response for errors, raising
|
||||
:param check: check the response for errors, raising
|
||||
:class:`~pymongo.errors.OperationFailure` if there are any
|
||||
- `allowable_errors`: if `check` is ``True``, error messages
|
||||
:param allowable_errors: if `check` is ``True``, error messages
|
||||
in this list will be ignored by error-checking
|
||||
- `read_preference` (optional): The read preference for this
|
||||
:param read_preference: The read preference for this
|
||||
operation. See :mod:`~pymongo.read_preferences` for options.
|
||||
If the provided `session` is in a transaction, defaults to the
|
||||
read preference configured for the transaction.
|
||||
Otherwise, defaults to
|
||||
:attr:`~pymongo.read_preferences.ReadPreference.PRIMARY`.
|
||||
- `codec_options`: A :class:`~bson.codec_options.CodecOptions`
|
||||
:param codec_options: A :class:`~bson.codec_options.CodecOptions`
|
||||
instance.
|
||||
- `session` (optional): A
|
||||
:param session: A
|
||||
:class:`~pymongo.client_session.ClientSession`.
|
||||
- `comment` (optional): A user-provided comment to attach to this
|
||||
:param comment: A user-provided comment to attach to this
|
||||
command.
|
||||
- `**kwargs` (optional): additional keyword arguments will
|
||||
:param kwargs: additional keyword arguments will
|
||||
be added to the command document before it is sent
|
||||
|
||||
|
||||
@ -924,8 +913,7 @@ class Database(common.BaseObject, Generic[_DocumentType]):
|
||||
|
||||
Otherwise, behaves identically to issuing a normal MongoDB command.
|
||||
|
||||
:Parameters:
|
||||
- `command`: document representing the command to be issued,
|
||||
:param command: document representing the command to be issued,
|
||||
or the name of the command (for simple commands only).
|
||||
|
||||
.. note:: the order of keys in the `command` document is
|
||||
@ -934,23 +922,23 @@ class Database(common.BaseObject, Generic[_DocumentType]):
|
||||
should use an instance of :class:`~bson.son.SON` or
|
||||
a string and kwargs instead of a Python `dict`.
|
||||
|
||||
- `value` (optional): value to use for the command verb when
|
||||
`command` is passed as a string
|
||||
- `read_preference` (optional): The read preference for this
|
||||
operation. See :mod:`~pymongo.read_preferences` for options.
|
||||
If the provided `session` is in a transaction, defaults to the
|
||||
read preference configured for the transaction.
|
||||
Otherwise, defaults to
|
||||
:attr:`~pymongo.read_preferences.ReadPreference.PRIMARY`.
|
||||
- `codec_options`: A :class:`~bson.codec_options.CodecOptions`
|
||||
instance.
|
||||
- `session` (optional): A
|
||||
:class:`~pymongo.client_session.ClientSession`.
|
||||
- `comment` (optional): A user-provided comment to attach to future getMores for this
|
||||
command.
|
||||
- `max_await_time_ms` (optional): The number of ms to wait for more data on future getMores for this command.
|
||||
- `**kwargs` (optional): additional keyword arguments will
|
||||
be added to the command document before it is sent
|
||||
:param value: value to use for the command verb when
|
||||
`command` is passed as a string
|
||||
:param read_preference: The read preference for this
|
||||
operation. See :mod:`~pymongo.read_preferences` for options.
|
||||
If the provided `session` is in a transaction, defaults to the
|
||||
read preference configured for the transaction.
|
||||
Otherwise, defaults to
|
||||
:attr:`~pymongo.read_preferences.ReadPreference.PRIMARY`.
|
||||
:param codec_options`: A :class:`~bson.codec_options.CodecOptions`
|
||||
instance.
|
||||
:param session: A
|
||||
:class:`~pymongo.client_session.ClientSession`.
|
||||
:param comment: A user-provided comment to attach to future getMores for this
|
||||
command.
|
||||
:param max_await_time_ms: The number of ms to wait for more data on future getMores for this command.
|
||||
:param kwargs: additional keyword arguments will
|
||||
be added to the command document before it is sent
|
||||
|
||||
.. note:: :meth:`command` does **not** obey this Database's
|
||||
:attr:`read_preference` or :attr:`codec_options`. You must use the
|
||||
@ -1066,22 +1054,20 @@ class Database(common.BaseObject, Generic[_DocumentType]):
|
||||
) -> CommandCursor[MutableMapping[str, Any]]:
|
||||
"""Get a cursor over the collections of this database.
|
||||
|
||||
:Parameters:
|
||||
- `session` (optional): a
|
||||
:param session: a
|
||||
:class:`~pymongo.client_session.ClientSession`.
|
||||
- `filter` (optional): A query document to filter the list of
|
||||
:param filter: A query document to filter the list of
|
||||
collections returned from the listCollections command.
|
||||
- `comment` (optional): A user-provided comment to attach to this
|
||||
:param comment: A user-provided comment to attach to this
|
||||
command.
|
||||
- `**kwargs` (optional): Optional parameters of the
|
||||
:param kwargs: Optional parameters of the
|
||||
`listCollections command
|
||||
<https://mongodb.com/docs/manual/reference/command/listCollections/>`_
|
||||
can be passed as keyword arguments to this method. The supported
|
||||
options differ by server version.
|
||||
|
||||
|
||||
:Returns:
|
||||
An instance of :class:`~pymongo.command_cursor.CommandCursor`.
|
||||
:return: An instance of :class:`~pymongo.command_cursor.CommandCursor`.
|
||||
|
||||
.. versionadded:: 3.6
|
||||
"""
|
||||
@ -1115,14 +1101,13 @@ class Database(common.BaseObject, Generic[_DocumentType]):
|
||||
filter = {"name": {"$regex": r"^(?!system\\.)"}}
|
||||
db.list_collection_names(filter=filter)
|
||||
|
||||
:Parameters:
|
||||
- `session` (optional): a
|
||||
:param session: a
|
||||
:class:`~pymongo.client_session.ClientSession`.
|
||||
- `filter` (optional): A query document to filter the list of
|
||||
:param filter: A query document to filter the list of
|
||||
collections returned from the listCollections command.
|
||||
- `comment` (optional): A user-provided comment to attach to this
|
||||
:param comment: A user-provided comment to attach to this
|
||||
command.
|
||||
- `**kwargs` (optional): Optional parameters of the
|
||||
:param kwargs: Optional parameters of the
|
||||
`listCollections command
|
||||
<https://mongodb.com/docs/manual/reference/command/listCollections/>`_
|
||||
can be passed as keyword arguments to this method. The supported
|
||||
@ -1176,14 +1161,13 @@ class Database(common.BaseObject, Generic[_DocumentType]):
|
||||
) -> dict[str, Any]:
|
||||
"""Drop a collection.
|
||||
|
||||
:Parameters:
|
||||
- `name_or_collection`: the name of a collection to drop or the
|
||||
:param name_or_collection: the name of a collection to drop or the
|
||||
collection object itself
|
||||
- `session` (optional): a
|
||||
:param session: a
|
||||
:class:`~pymongo.client_session.ClientSession`.
|
||||
- `comment` (optional): A user-provided comment to attach to this
|
||||
:param comment: A user-provided comment to attach to this
|
||||
command.
|
||||
- `encrypted_fields`: **(BETA)** Document that describes the encrypted fields for
|
||||
:param encrypted_fields: **(BETA)** Document that describes the encrypted fields for
|
||||
Queryable Encryption. For example::
|
||||
|
||||
{
|
||||
@ -1261,20 +1245,19 @@ class Database(common.BaseObject, Generic[_DocumentType]):
|
||||
|
||||
See also the MongoDB documentation on the `validate command`_.
|
||||
|
||||
:Parameters:
|
||||
- `name_or_collection`: A Collection object or the name of a
|
||||
:param name_or_collection: A Collection object or the name of a
|
||||
collection to validate.
|
||||
- `scandata`: Do extra checks beyond checking the overall
|
||||
:param scandata: Do extra checks beyond checking the overall
|
||||
structure of the collection.
|
||||
- `full`: Have the server do a more thorough scan of the
|
||||
:param full: Have the server do a more thorough scan of the
|
||||
collection. Use with `scandata` for a thorough scan
|
||||
of the structure of the collection and the individual
|
||||
documents.
|
||||
- `session` (optional): a
|
||||
:param session: a
|
||||
:class:`~pymongo.client_session.ClientSession`.
|
||||
- `background` (optional): A boolean flag that determines whether
|
||||
:param background: A boolean flag that determines whether
|
||||
the command runs in the background. Requires MongoDB 4.4+.
|
||||
- `comment` (optional): A user-provided comment to attach to this
|
||||
:param comment: A user-provided comment to attach to this
|
||||
command.
|
||||
|
||||
.. versionchanged:: 4.1
|
||||
@ -1359,13 +1342,12 @@ class Database(common.BaseObject, Generic[_DocumentType]):
|
||||
:class:`ValueError` if `dbref` has a database specified that
|
||||
is different from the current database.
|
||||
|
||||
:Parameters:
|
||||
- `dbref`: the reference
|
||||
- `session` (optional): a
|
||||
:param dbref: the reference
|
||||
:param session: a
|
||||
:class:`~pymongo.client_session.ClientSession`.
|
||||
- `comment` (optional): A user-provided comment to attach to this
|
||||
:param comment: A user-provided comment to attach to this
|
||||
command.
|
||||
- `**kwargs` (optional): any additional keyword arguments
|
||||
:param kwargs: any additional keyword arguments
|
||||
are the same as the arguments to
|
||||
:meth:`~pymongo.collection.Collection.find`.
|
||||
|
||||
|
||||
@ -135,11 +135,9 @@ class _EncryptionIO(MongoCryptCallback): # type: ignore[misc]
|
||||
def kms_request(self, kms_context: MongoCryptKmsContext) -> None:
|
||||
"""Complete a KMS request.
|
||||
|
||||
:Parameters:
|
||||
- `kms_context`: A :class:`MongoCryptKmsContext`.
|
||||
:param kms_context: A :class:`MongoCryptKmsContext`.
|
||||
|
||||
:Returns:
|
||||
None
|
||||
:return: None
|
||||
"""
|
||||
endpoint = kms_context.endpoint
|
||||
message = kms_context.message
|
||||
@ -194,12 +192,10 @@ class _EncryptionIO(MongoCryptCallback): # type: ignore[misc]
|
||||
The returned collection info is passed to libmongocrypt which reads
|
||||
the JSON schema.
|
||||
|
||||
:Parameters:
|
||||
- `database`: The database on which to run listCollections.
|
||||
- `filter`: The filter to pass to listCollections.
|
||||
:param database: The database on which to run listCollections.
|
||||
:param filter: The filter to pass to listCollections.
|
||||
|
||||
:Returns:
|
||||
The first document from the listCollections command response as BSON.
|
||||
:return: The first document from the listCollections command response as BSON.
|
||||
"""
|
||||
with self.client_ref()[database].list_collections(filter=RawBSONDocument(filter)) as cursor:
|
||||
for doc in cursor:
|
||||
@ -220,12 +216,10 @@ class _EncryptionIO(MongoCryptCallback): # type: ignore[misc]
|
||||
def mark_command(self, database: str, cmd: bytes) -> bytes:
|
||||
"""Mark a command for encryption.
|
||||
|
||||
:Parameters:
|
||||
- `database`: The database on which to run this command.
|
||||
- `cmd`: The BSON command to run.
|
||||
:param database: The database on which to run this command.
|
||||
:param cmd: The BSON command to run.
|
||||
|
||||
:Returns:
|
||||
The marked command response from mongocryptd.
|
||||
:return: The marked command response from mongocryptd.
|
||||
"""
|
||||
if not self._spawned and not self.opts._mongocryptd_bypass_spawn:
|
||||
self.spawn()
|
||||
@ -249,11 +243,9 @@ class _EncryptionIO(MongoCryptCallback): # type: ignore[misc]
|
||||
def fetch_keys(self, filter: bytes) -> Iterator[bytes]:
|
||||
"""Yields one or more keys from the key vault.
|
||||
|
||||
:Parameters:
|
||||
- `filter`: The filter to pass to find.
|
||||
:param filter: The filter to pass to find.
|
||||
|
||||
:Returns:
|
||||
A generator which yields the requested keys from the key vault.
|
||||
:return: A generator which yields the requested keys from the key vault.
|
||||
"""
|
||||
assert self.key_vault_coll is not None
|
||||
with self.key_vault_coll.find(RawBSONDocument(filter)) as cursor:
|
||||
@ -263,11 +255,9 @@ class _EncryptionIO(MongoCryptCallback): # type: ignore[misc]
|
||||
def insert_data_key(self, data_key: bytes) -> Binary:
|
||||
"""Insert a data key into the key vault.
|
||||
|
||||
:Parameters:
|
||||
- `data_key`: The data key document to insert.
|
||||
:param data_key: The data key document to insert.
|
||||
|
||||
:Returns:
|
||||
The _id of the inserted data key document.
|
||||
:return: The _id of the inserted data key document.
|
||||
"""
|
||||
raw_doc = RawBSONDocument(data_key, _KEY_VAULT_OPTS)
|
||||
data_key_id = raw_doc.get("_id")
|
||||
@ -283,11 +273,9 @@ class _EncryptionIO(MongoCryptCallback): # type: ignore[misc]
|
||||
|
||||
A document can be any mapping type (like :class:`dict`).
|
||||
|
||||
:Parameters:
|
||||
- `doc`: mapping type representing a document
|
||||
:param doc: mapping type representing a document
|
||||
|
||||
:Returns:
|
||||
The encoded BSON bytes.
|
||||
:return: The encoded BSON bytes.
|
||||
"""
|
||||
return encode(doc)
|
||||
|
||||
@ -336,9 +324,8 @@ class _Encrypter:
|
||||
def __init__(self, client: MongoClient[_DocumentTypeArg], opts: AutoEncryptionOpts):
|
||||
"""Create a _Encrypter for a client.
|
||||
|
||||
:Parameters:
|
||||
- `client`: The encrypted MongoClient.
|
||||
- `opts`: The encrypted client's :class:`AutoEncryptionOpts`.
|
||||
:param client: The encrypted MongoClient.
|
||||
:param opts: The encrypted client's :class:`AutoEncryptionOpts`.
|
||||
"""
|
||||
if opts._schema_map is None:
|
||||
schema_map = None
|
||||
@ -404,13 +391,11 @@ class _Encrypter:
|
||||
) -> MutableMapping[str, Any]:
|
||||
"""Encrypt a MongoDB command.
|
||||
|
||||
:Parameters:
|
||||
- `database`: The database for this command.
|
||||
- `cmd`: A command document.
|
||||
- `codec_options`: The CodecOptions to use while encoding `cmd`.
|
||||
:param database: The database for this command.
|
||||
:param cmd: A command document.
|
||||
:param codec_options: The CodecOptions to use while encoding `cmd`.
|
||||
|
||||
:Returns:
|
||||
The encrypted command to execute.
|
||||
:return: The encrypted command to execute.
|
||||
"""
|
||||
self._check_closed()
|
||||
encoded_cmd = _dict_to_bson(cmd, False, codec_options)
|
||||
@ -422,11 +407,9 @@ class _Encrypter:
|
||||
def decrypt(self, response: bytes) -> Optional[bytes]:
|
||||
"""Decrypt a MongoDB command response.
|
||||
|
||||
:Parameters:
|
||||
- `response`: A MongoDB command response as BSON.
|
||||
:param response: A MongoDB command response as BSON.
|
||||
|
||||
:Returns:
|
||||
The decrypted command response.
|
||||
:return: The decrypted command response.
|
||||
"""
|
||||
self._check_closed()
|
||||
with _wrap_encryption_errors():
|
||||
@ -513,8 +496,7 @@ class ClientEncryption(Generic[_DocumentType]):
|
||||
|
||||
See :ref:`explicit-client-side-encryption` for an example.
|
||||
|
||||
:Parameters:
|
||||
- `kms_providers`: Map of KMS provider options. The `kms_providers`
|
||||
:param kms_providers: Map of KMS provider options. The `kms_providers`
|
||||
map values differ by provider:
|
||||
|
||||
- `aws`: Map with "accessKeyId" and "secretAccessKey" as strings.
|
||||
@ -539,20 +521,20 @@ class ClientEncryption(Generic[_DocumentType]):
|
||||
data keys. This key should be generated and stored as securely
|
||||
as possible.
|
||||
|
||||
- `key_vault_namespace`: The namespace for the key vault collection.
|
||||
:param key_vault_namespace: The namespace for the key vault collection.
|
||||
The key vault collection contains all data keys used for encryption
|
||||
and decryption. Data keys are stored as documents in this MongoDB
|
||||
collection. Data keys are protected with encryption by a KMS
|
||||
provider.
|
||||
- `key_vault_client`: A MongoClient connected to a MongoDB cluster
|
||||
:param key_vault_client: A MongoClient connected to a MongoDB cluster
|
||||
containing the `key_vault_namespace` collection.
|
||||
- `codec_options`: An instance of
|
||||
:param codec_options: An instance of
|
||||
:class:`~bson.codec_options.CodecOptions` to use when encoding a
|
||||
value for encryption and decoding the decrypted BSON value. This
|
||||
should be the same CodecOptions instance configured on the
|
||||
MongoClient, Database, or Collection used to access application
|
||||
data.
|
||||
- `kms_tls_options` (optional): A map of KMS provider names to TLS
|
||||
:param kms_tls_options: A map of KMS provider names to TLS
|
||||
options to use when creating secure connections to KMS providers.
|
||||
Accepts the same TLS options as
|
||||
:class:`pymongo.mongo_client.MongoClient`. For example, to
|
||||
@ -621,10 +603,11 @@ class ClientEncryption(Generic[_DocumentType]):
|
||||
creation. :class:`~pymongo.errors.EncryptionError` will be
|
||||
raised if the collection already exists.
|
||||
|
||||
:Parameters:
|
||||
- `name`: the name of the collection to create
|
||||
- `encrypted_fields` (dict): Document that describes the encrypted fields for
|
||||
Queryable Encryption. For example::
|
||||
:param name: the name of the collection to create
|
||||
:param encrypted_fields: Document that describes the encrypted fields for
|
||||
Queryable Encryption. The "keyId" may be set to ``None`` to auto-generate the data keys. For example:
|
||||
|
||||
.. code-block: python
|
||||
|
||||
{
|
||||
"escCollection": "enxcol_.encryptedCollection.esc",
|
||||
@ -644,19 +627,17 @@ class ClientEncryption(Generic[_DocumentType]):
|
||||
]
|
||||
}
|
||||
|
||||
The "keyId" may be set to ``None`` to auto-generate the data keys.
|
||||
- `kms_provider` (optional): the KMS provider to be used
|
||||
- `master_key` (optional): Identifies a KMS-specific key used to encrypt the
|
||||
:param kms_provider: the KMS provider to be used
|
||||
:param master_key: Identifies a KMS-specific key used to encrypt the
|
||||
new data key. If the kmsProvider is "local" the `master_key` is
|
||||
not applicable and may be omitted.
|
||||
- `**kwargs` (optional): additional keyword arguments are the same as "create_collection".
|
||||
:param kwargs: additional keyword arguments are the same as "create_collection".
|
||||
|
||||
All optional `create collection command`_ parameters should be passed
|
||||
as keyword arguments to this method.
|
||||
See the documentation for :meth:`~pymongo.database.Database.create_collection` for all valid options.
|
||||
|
||||
:Raises:
|
||||
- :class:`~pymongo.errors.EncryptedCollectionError`: When either data-key creation or creating the collection fails.
|
||||
:raises: - :class:`~pymongo.errors.EncryptedCollectionError`: When either data-key creation or creating the collection fails.
|
||||
|
||||
.. versionadded:: 4.4
|
||||
|
||||
@ -693,10 +674,9 @@ class ClientEncryption(Generic[_DocumentType]):
|
||||
) -> Binary:
|
||||
"""Create and insert a new data key into the key vault collection.
|
||||
|
||||
:Parameters:
|
||||
- `kms_provider`: The KMS provider to use. Supported values are
|
||||
:param kms_provider: The KMS provider to use. Supported values are
|
||||
"aws", "azure", "gcp", "kmip", and "local".
|
||||
- `master_key`: Identifies a KMS-specific key used to encrypt the
|
||||
:param master_key: Identifies a KMS-specific key used to encrypt the
|
||||
new data key. If the kmsProvider is "local" the `master_key` is
|
||||
not applicable and may be omitted.
|
||||
|
||||
@ -740,7 +720,7 @@ class ClientEncryption(Generic[_DocumentType]):
|
||||
- `endpoint` (string): Optional. Host with optional
|
||||
port, e.g. "example.vault.azure.net:".
|
||||
|
||||
- `key_alt_names` (optional): An optional list of string alternate
|
||||
:param key_alt_names: An optional list of string alternate
|
||||
names used to reference a key. If a key is created with alternate
|
||||
names, then encryption may refer to the key by the unique alternate
|
||||
name instead of by ``key_id``. The following example shows creating
|
||||
@ -750,11 +730,10 @@ class ClientEncryption(Generic[_DocumentType]):
|
||||
# reference the key with the alternate name
|
||||
client_encryption.encrypt("457-55-5462", key_alt_name="name1",
|
||||
algorithm=Algorithm.AEAD_AES_256_CBC_HMAC_SHA_512_Random)
|
||||
- `key_material` (optional): Sets the custom key material to be used
|
||||
:param key_material: Sets the custom key material to be used
|
||||
by the data key for encryption and decryption.
|
||||
|
||||
:Returns:
|
||||
The ``_id`` of the created data key document as a
|
||||
:return: The ``_id`` of the created data key document as a
|
||||
:class:`~bson.binary.Binary` with subtype
|
||||
:data:`~bson.binary.UUID_SUBTYPE`.
|
||||
|
||||
@ -828,23 +807,21 @@ class ClientEncryption(Generic[_DocumentType]):
|
||||
Note that exactly one of ``key_id`` or ``key_alt_name`` must be
|
||||
provided.
|
||||
|
||||
:Parameters:
|
||||
- `value`: The BSON value to encrypt.
|
||||
- `algorithm` (string): The encryption algorithm to use. See
|
||||
:param value: The BSON value to encrypt.
|
||||
:param algorithm` (string): The encryption algorithm to use. See
|
||||
:class:`Algorithm` for some valid options.
|
||||
- `key_id`: Identifies a data key by ``_id`` which must be a
|
||||
:param key_id: Identifies a data key by ``_id`` which must be a
|
||||
:class:`~bson.binary.Binary` with subtype 4 (
|
||||
:attr:`~bson.binary.UUID_SUBTYPE`).
|
||||
- `key_alt_name`: Identifies a key vault document by 'keyAltName'.
|
||||
- `query_type` (str): The query type to execute. See :class:`QueryType` for valid options.
|
||||
- `contention_factor` (int): The contention factor to use
|
||||
:param key_alt_name: Identifies a key vault document by 'keyAltName'.
|
||||
:param query_type` (str): The query type to execute. See :class:`QueryType` for valid options.
|
||||
:param contention_factor` (int): The contention factor to use
|
||||
when the algorithm is :attr:`Algorithm.INDEXED`. An integer value
|
||||
*must* be given when the :attr:`Algorithm.INDEXED` algorithm is
|
||||
used.
|
||||
- `range_opts`: Experimental only, not intended for public use.
|
||||
:param range_opts: Experimental only, not intended for public use.
|
||||
|
||||
:Returns:
|
||||
The encrypted value, a :class:`~bson.binary.Binary` with subtype 6.
|
||||
:return: The encrypted value, a :class:`~bson.binary.Binary` with subtype 6.
|
||||
|
||||
.. versionchanged:: 4.2
|
||||
Added the `query_type` and `contention_factor` parameters.
|
||||
@ -878,24 +855,22 @@ class ClientEncryption(Generic[_DocumentType]):
|
||||
Note that exactly one of ``key_id`` or ``key_alt_name`` must be
|
||||
provided.
|
||||
|
||||
:Parameters:
|
||||
- `expression`: The BSON aggregate or match expression to encrypt.
|
||||
- `algorithm` (string): The encryption algorithm to use. See
|
||||
:param expression: The BSON aggregate or match expression to encrypt.
|
||||
:param algorithm` (string): The encryption algorithm to use. See
|
||||
:class:`Algorithm` for some valid options.
|
||||
- `key_id`: Identifies a data key by ``_id`` which must be a
|
||||
:param key_id: Identifies a data key by ``_id`` which must be a
|
||||
:class:`~bson.binary.Binary` with subtype 4 (
|
||||
:attr:`~bson.binary.UUID_SUBTYPE`).
|
||||
- `key_alt_name`: Identifies a key vault document by 'keyAltName'.
|
||||
- `query_type` (str): The query type to execute. See
|
||||
:param key_alt_name: Identifies a key vault document by 'keyAltName'.
|
||||
:param query_type` (str): The query type to execute. See
|
||||
:class:`QueryType` for valid options.
|
||||
- `contention_factor` (int): The contention factor to use
|
||||
:param contention_factor` (int): The contention factor to use
|
||||
when the algorithm is :attr:`Algorithm.INDEXED`. An integer value
|
||||
*must* be given when the :attr:`Algorithm.INDEXED` algorithm is
|
||||
used.
|
||||
- `range_opts`: Experimental only, not intended for public use.
|
||||
:param range_opts: Experimental only, not intended for public use.
|
||||
|
||||
:Returns:
|
||||
The encrypted expression, a :class:`~bson.RawBSONDocument`.
|
||||
:return: The encrypted expression, a :class:`~bson.RawBSONDocument`.
|
||||
|
||||
.. versionadded:: 4.4
|
||||
"""
|
||||
@ -916,12 +891,10 @@ class ClientEncryption(Generic[_DocumentType]):
|
||||
def decrypt(self, value: Binary) -> Any:
|
||||
"""Decrypt an encrypted value.
|
||||
|
||||
:Parameters:
|
||||
- `value` (Binary): The encrypted value, a
|
||||
:param value` (Binary): The encrypted value, a
|
||||
:class:`~bson.binary.Binary` with subtype 6.
|
||||
|
||||
:Returns:
|
||||
The decrypted BSON value.
|
||||
:return: The decrypted BSON value.
|
||||
"""
|
||||
self._check_closed()
|
||||
if not (isinstance(value, Binary) and value.subtype == 6):
|
||||
@ -935,13 +908,11 @@ class ClientEncryption(Generic[_DocumentType]):
|
||||
def get_key(self, id: Binary) -> Optional[RawBSONDocument]:
|
||||
"""Get a data key by id.
|
||||
|
||||
:Parameters:
|
||||
- `id` (Binary): The UUID of a key a which must be a
|
||||
:param id` (Binary): The UUID of a key a which must be a
|
||||
:class:`~bson.binary.Binary` with subtype 4 (
|
||||
:attr:`~bson.binary.UUID_SUBTYPE`).
|
||||
|
||||
:Returns:
|
||||
The key document.
|
||||
:return: The key document.
|
||||
|
||||
.. versionadded:: 4.2
|
||||
"""
|
||||
@ -952,8 +923,7 @@ class ClientEncryption(Generic[_DocumentType]):
|
||||
def get_keys(self) -> Cursor[RawBSONDocument]:
|
||||
"""Get all of the data keys.
|
||||
|
||||
:Returns:
|
||||
An instance of :class:`~pymongo.cursor.Cursor` over the data key
|
||||
:return: An instance of :class:`~pymongo.cursor.Cursor` over the data key
|
||||
documents.
|
||||
|
||||
.. versionadded:: 4.2
|
||||
@ -965,13 +935,11 @@ class ClientEncryption(Generic[_DocumentType]):
|
||||
def delete_key(self, id: Binary) -> DeleteResult:
|
||||
"""Delete a key document in the key vault collection that has the given ``key_id``.
|
||||
|
||||
:Parameters:
|
||||
- `id` (Binary): The UUID of a key a which must be a
|
||||
:param id` (Binary): The UUID of a key a which must be a
|
||||
:class:`~bson.binary.Binary` with subtype 4 (
|
||||
:attr:`~bson.binary.UUID_SUBTYPE`).
|
||||
|
||||
:Returns:
|
||||
The delete result.
|
||||
:return: The delete result.
|
||||
|
||||
.. versionadded:: 4.2
|
||||
"""
|
||||
@ -982,14 +950,12 @@ class ClientEncryption(Generic[_DocumentType]):
|
||||
def add_key_alt_name(self, id: Binary, key_alt_name: str) -> Any:
|
||||
"""Add ``key_alt_name`` to the set of alternate names in the key document with UUID ``key_id``.
|
||||
|
||||
:Parameters:
|
||||
- ``id``: The UUID of a key a which must be a
|
||||
:param `id`: The UUID of a key a which must be a
|
||||
:class:`~bson.binary.Binary` with subtype 4 (
|
||||
:attr:`~bson.binary.UUID_SUBTYPE`).
|
||||
- ``key_alt_name``: The key alternate name to add.
|
||||
:param `key_alt_name`: The key alternate name to add.
|
||||
|
||||
:Returns:
|
||||
The previous version of the key document.
|
||||
:return: The previous version of the key document.
|
||||
|
||||
.. versionadded:: 4.2
|
||||
"""
|
||||
@ -1001,11 +967,9 @@ class ClientEncryption(Generic[_DocumentType]):
|
||||
def get_key_by_alt_name(self, key_alt_name: str) -> Optional[RawBSONDocument]:
|
||||
"""Get a key document in the key vault collection that has the given ``key_alt_name``.
|
||||
|
||||
:Parameters:
|
||||
- `key_alt_name`: (str): The key alternate name of the key to get.
|
||||
:param key_alt_name: (str): The key alternate name of the key to get.
|
||||
|
||||
:Returns:
|
||||
The key document.
|
||||
:return: The key document.
|
||||
|
||||
.. versionadded:: 4.2
|
||||
"""
|
||||
@ -1018,14 +982,12 @@ class ClientEncryption(Generic[_DocumentType]):
|
||||
|
||||
Also removes the ``keyAltNames`` field from the key document if it would otherwise be empty.
|
||||
|
||||
:Parameters:
|
||||
- ``id``: The UUID of a key a which must be a
|
||||
:param `id`: The UUID of a key a which must be a
|
||||
:class:`~bson.binary.Binary` with subtype 4 (
|
||||
:attr:`~bson.binary.UUID_SUBTYPE`).
|
||||
- ``key_alt_name``: The key alternate name to remove.
|
||||
:param `key_alt_name`: The key alternate name to remove.
|
||||
|
||||
:Returns:
|
||||
Returns the previous version of the key document.
|
||||
:return: Returns the previous version of the key document.
|
||||
|
||||
.. versionadded:: 4.2
|
||||
"""
|
||||
@ -1059,15 +1021,13 @@ class ClientEncryption(Generic[_DocumentType]):
|
||||
) -> RewrapManyDataKeyResult:
|
||||
"""Decrypts and encrypts all matching data keys in the key vault with a possibly new `master_key` value.
|
||||
|
||||
:Parameters:
|
||||
- `filter`: A document used to filter the data keys.
|
||||
- `provider`: The new KMS provider to use to encrypt the data keys,
|
||||
:param filter: A document used to filter the data keys.
|
||||
:param provider: The new KMS provider to use to encrypt the data keys,
|
||||
or ``None`` to use the current KMS provider(s).
|
||||
- ``master_key``: The master key fields corresponding to the new KMS
|
||||
:param `master_key`: The master key fields corresponding to the new KMS
|
||||
provider when ``provider`` is not ``None``.
|
||||
|
||||
:Returns:
|
||||
A :class:`RewrapManyDataKeyResult`.
|
||||
:return: A :class:`RewrapManyDataKeyResult`.
|
||||
|
||||
This method allows you to re-encrypt all of your data-keys with a new CMK, or master key.
|
||||
Note that this does *not* require re-encrypting any of the data in your encrypted collections,
|
||||
|
||||
@ -69,8 +69,7 @@ class AutoEncryptionOpts:
|
||||
|
||||
See :ref:`automatic-client-side-encryption` for an example.
|
||||
|
||||
:Parameters:
|
||||
- `kms_providers`: Map of KMS provider options. The `kms_providers`
|
||||
:param kms_providers: Map of KMS provider options. The `kms_providers`
|
||||
map values differ by provider:
|
||||
|
||||
- `aws`: Map with "accessKeyId" and "secretAccessKey" as strings.
|
||||
@ -95,16 +94,16 @@ class AutoEncryptionOpts:
|
||||
data keys. This key should be generated and stored as securely
|
||||
as possible.
|
||||
|
||||
- `key_vault_namespace`: The namespace for the key vault collection.
|
||||
:param key_vault_namespace: The namespace for the key vault collection.
|
||||
The key vault collection contains all data keys used for encryption
|
||||
and decryption. Data keys are stored as documents in this MongoDB
|
||||
collection. Data keys are protected with encryption by a KMS
|
||||
provider.
|
||||
- `key_vault_client` (optional): By default the key vault collection
|
||||
:param key_vault_client: By default the key vault collection
|
||||
is assumed to reside in the same MongoDB cluster as the encrypted
|
||||
MongoClient. Use this option to route data key queries to a
|
||||
separate MongoDB cluster.
|
||||
- `schema_map` (optional): Map of collection namespace ("db.coll") to
|
||||
:param schema_map: Map of collection namespace ("db.coll") to
|
||||
JSON Schema. By default, a collection's JSONSchema is periodically
|
||||
polled with the listCollections command. But a JSONSchema may be
|
||||
specified locally with the schemaMap option.
|
||||
@ -119,24 +118,24 @@ class AutoEncryptionOpts:
|
||||
automatic encryption for client side encryption. Other validation
|
||||
rules in the JSON schema will not be enforced by the driver and
|
||||
will result in an error.
|
||||
- `bypass_auto_encryption` (optional): If ``True``, automatic
|
||||
:param bypass_auto_encryption: If ``True``, automatic
|
||||
encryption will be disabled but automatic decryption will still be
|
||||
enabled. Defaults to ``False``.
|
||||
- `mongocryptd_uri` (optional): The MongoDB URI used to connect
|
||||
:param mongocryptd_uri: The MongoDB URI used to connect
|
||||
to the *local* mongocryptd process. Defaults to
|
||||
``'mongodb://localhost:27020'``.
|
||||
- `mongocryptd_bypass_spawn` (optional): If ``True``, the encrypted
|
||||
:param mongocryptd_bypass_spawn: If ``True``, the encrypted
|
||||
MongoClient will not attempt to spawn the mongocryptd process.
|
||||
Defaults to ``False``.
|
||||
- `mongocryptd_spawn_path` (optional): Used for spawning the
|
||||
:param mongocryptd_spawn_path: Used for spawning the
|
||||
mongocryptd process. Defaults to ``'mongocryptd'`` and spawns
|
||||
mongocryptd from the system path.
|
||||
- `mongocryptd_spawn_args` (optional): A list of string arguments to
|
||||
:param mongocryptd_spawn_args: A list of string arguments to
|
||||
use when spawning the mongocryptd process. Defaults to
|
||||
``['--idleShutdownTimeoutSecs=60']``. If the list does not include
|
||||
the ``idleShutdownTimeoutSecs`` option then
|
||||
``'--idleShutdownTimeoutSecs=60'`` will be added.
|
||||
- `kms_tls_options` (optional): A map of KMS provider names to TLS
|
||||
:param kms_tls_options: A map of KMS provider names to TLS
|
||||
options to use when creating secure connections to KMS providers.
|
||||
Accepts the same TLS options as
|
||||
:class:`pymongo.mongo_client.MongoClient`. For example, to
|
||||
@ -147,14 +146,14 @@ class AutoEncryptionOpts:
|
||||
Or to supply a client certificate::
|
||||
|
||||
kms_tls_options={'kmip': {'tlsCertificateKeyFile': 'client.pem'}}
|
||||
- `crypt_shared_lib_path` (optional): Override the path to load the crypt_shared library.
|
||||
- `crypt_shared_lib_required` (optional): If True, raise an error if libmongocrypt is
|
||||
:param crypt_shared_lib_path: Override the path to load the crypt_shared library.
|
||||
:param crypt_shared_lib_required: If True, raise an error if libmongocrypt is
|
||||
unable to load the crypt_shared library.
|
||||
- `bypass_query_analysis` (optional): If ``True``, disable automatic analysis
|
||||
:param bypass_query_analysis: If ``True``, disable automatic analysis
|
||||
of outgoing commands. Set `bypass_query_analysis` to use explicit
|
||||
encryption on indexed fields without the MongoDB Enterprise Advanced
|
||||
licensed crypt_shared library.
|
||||
- `encrypted_fields_map`: Map of collection namespace ("db.coll") to documents
|
||||
:param encrypted_fields_map: Map of collection namespace ("db.coll") to documents
|
||||
that described the encrypted fields for Queryable Encryption. For example::
|
||||
|
||||
{
|
||||
@ -232,11 +231,10 @@ class RangeOpts:
|
||||
|
||||
.. note:: This feature is experimental only, and not intended for public use.
|
||||
|
||||
:Parameters:
|
||||
- `sparsity`: An integer.
|
||||
- `min`: A BSON scalar value corresponding to the type being queried.
|
||||
- `max`: A BSON scalar value corresponding to the type being queried.
|
||||
- `precision`: An integer, may only be set for double or decimal128 types.
|
||||
:param sparsity: An integer.
|
||||
:param min: A BSON scalar value corresponding to the type being queried.
|
||||
:param max: A BSON scalar value corresponding to the type being queried.
|
||||
:param precision: An integer, may only be set for double or decimal128 types.
|
||||
|
||||
.. versionadded:: 4.4
|
||||
"""
|
||||
|
||||
@ -1475,8 +1475,7 @@ class _OpReply:
|
||||
Can raise CursorNotFound, NotPrimaryError, ExecutionTimeout, or
|
||||
OperationFailure.
|
||||
|
||||
:Parameters:
|
||||
- `cursor_id` (optional): cursor_id we sent to get this response -
|
||||
:param cursor_id: cursor_id we sent to get this response -
|
||||
used for raising an informative exception when we get cursor id not
|
||||
valid at server response.
|
||||
"""
|
||||
@ -1525,13 +1524,12 @@ class _OpReply:
|
||||
Can raise CursorNotFound, NotPrimaryError, ExecutionTimeout, or
|
||||
OperationFailure.
|
||||
|
||||
:Parameters:
|
||||
- `cursor_id` (optional): cursor_id we sent to get this response -
|
||||
:param cursor_id: cursor_id we sent to get this response -
|
||||
used for raising an informative exception when we get cursor id not
|
||||
valid at server response
|
||||
- `codec_options` (optional): an instance of
|
||||
:param codec_options: an instance of
|
||||
:class:`~bson.codec_options.CodecOptions`
|
||||
- `user_fields` (optional): Response fields that should be decoded
|
||||
:param user_fields: Response fields that should be decoded
|
||||
using the TypeDecoders from codec_options, passed to
|
||||
bson._decode_all_selective.
|
||||
"""
|
||||
@ -1606,11 +1604,10 @@ class _OpMsg:
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Unpack a OP_MSG command response.
|
||||
|
||||
:Parameters:
|
||||
- `cursor_id` (optional): Ignored, for compatibility with _OpReply.
|
||||
- `codec_options` (optional): an instance of
|
||||
:param cursor_id: Ignored, for compatibility with _OpReply.
|
||||
:param codec_options: an instance of
|
||||
:class:`~bson.codec_options.CodecOptions`
|
||||
- `user_fields` (optional): Response fields that should be decoded
|
||||
:param user_fields: Response fields that should be decoded
|
||||
using the TypeDecoders from codec_options, passed to
|
||||
bson._decode_all_selective.
|
||||
"""
|
||||
|
||||
@ -246,28 +246,27 @@ class MongoClient(common.BaseObject, Generic[_DocumentType]):
|
||||
URI or keyword parameters. If the same option is passed in a URI and
|
||||
as a keyword parameter the keyword parameter takes precedence.
|
||||
|
||||
:Parameters:
|
||||
- `host` (optional): hostname or IP address or Unix domain socket
|
||||
:param host: hostname or IP address or Unix domain socket
|
||||
path of a single mongod or mongos instance to connect to, or a
|
||||
mongodb URI, or a list of hostnames (but no more than one mongodb
|
||||
URI). If `host` is an IPv6 literal it must be enclosed in '['
|
||||
and ']' characters
|
||||
following the RFC2732 URL syntax (e.g. '[::1]' for localhost).
|
||||
Multihomed and round robin DNS addresses are **not** supported.
|
||||
- `port` (optional): port number on which to connect
|
||||
- `document_class` (optional): default class to use for
|
||||
:param port: port number on which to connect
|
||||
:param document_class: default class to use for
|
||||
documents returned from queries on this client
|
||||
- `tz_aware` (optional): if ``True``,
|
||||
:param tz_aware: if ``True``,
|
||||
:class:`~datetime.datetime` instances returned as values
|
||||
in a document by this :class:`MongoClient` will be timezone
|
||||
aware (otherwise they will be naive)
|
||||
- `connect` (optional): if ``True`` (the default), immediately
|
||||
:param connect: if ``True`` (the default), immediately
|
||||
begin connecting to MongoDB in the background. Otherwise connect
|
||||
on the first operation.
|
||||
- `type_registry` (optional): instance of
|
||||
:param type_registry: instance of
|
||||
:class:`~bson.codec_options.TypeRegistry` to enable encoding
|
||||
and decoding of custom types.
|
||||
- `datetime_conversion`: Specifies how UTC datetimes should be decoded
|
||||
:param datetime_conversion: Specifies how UTC datetimes should be decoded
|
||||
within BSON. Valid options include 'datetime_ms' to return as a
|
||||
DatetimeMS, 'datetime' to return as a datetime.datetime and
|
||||
raising a ValueError for out-of-range values, 'datetime_auto' to
|
||||
@ -971,47 +970,45 @@ class MongoClient(common.BaseObject, Generic[_DocumentType]):
|
||||
For a precise description of the resume process see the
|
||||
`change streams specification`_.
|
||||
|
||||
:Parameters:
|
||||
- `pipeline` (optional): A list of aggregation pipeline stages to
|
||||
:param pipeline: A list of aggregation pipeline stages to
|
||||
append to an initial ``$changeStream`` stage. Not all
|
||||
pipeline stages are valid after a ``$changeStream`` stage, see the
|
||||
MongoDB documentation on change streams for the supported stages.
|
||||
- `full_document` (optional): The fullDocument to pass as an option
|
||||
:param full_document: The fullDocument to pass as an option
|
||||
to the ``$changeStream`` stage. Allowed values: 'updateLookup',
|
||||
'whenAvailable', 'required'. When set to 'updateLookup', the
|
||||
change notification for partial updates will include both a delta
|
||||
describing the changes to the document, as well as a copy of the
|
||||
entire document that was changed from some time after the change
|
||||
occurred.
|
||||
- `full_document_before_change`: Allowed values: 'whenAvailable'
|
||||
:param full_document_before_change: Allowed values: 'whenAvailable'
|
||||
and 'required'. Change events may now result in a
|
||||
'fullDocumentBeforeChange' response field.
|
||||
- `resume_after` (optional): A resume token. If provided, the
|
||||
:param resume_after: A resume token. If provided, the
|
||||
change stream will start returning changes that occur directly
|
||||
after the operation specified in the resume token. A resume token
|
||||
is the _id value of a change document.
|
||||
- `max_await_time_ms` (optional): The maximum time in milliseconds
|
||||
:param max_await_time_ms: The maximum time in milliseconds
|
||||
for the server to wait for changes before responding to a getMore
|
||||
operation.
|
||||
- `batch_size` (optional): The maximum number of documents to return
|
||||
:param batch_size: The maximum number of documents to return
|
||||
per batch.
|
||||
- `collation` (optional): The :class:`~pymongo.collation.Collation`
|
||||
:param collation: The :class:`~pymongo.collation.Collation`
|
||||
to use for the aggregation.
|
||||
- `start_at_operation_time` (optional): If provided, the resulting
|
||||
:param start_at_operation_time: If provided, the resulting
|
||||
change stream will only return changes that occurred at or after
|
||||
the specified :class:`~bson.timestamp.Timestamp`. Requires
|
||||
MongoDB >= 4.0.
|
||||
- `session` (optional): a
|
||||
:param session: a
|
||||
:class:`~pymongo.client_session.ClientSession`.
|
||||
- `start_after` (optional): The same as `resume_after` except that
|
||||
:param start_after: The same as `resume_after` except that
|
||||
`start_after` can resume notifications after an invalidate event.
|
||||
This option and `resume_after` are mutually exclusive.
|
||||
- `comment` (optional): A user-provided comment to attach to this
|
||||
:param comment: A user-provided comment to attach to this
|
||||
command.
|
||||
- `show_expanded_events` (optional): Include expanded events such as DDL events like `dropIndexes`.
|
||||
:param show_expanded_events: Include expanded events such as DDL events like `dropIndexes`.
|
||||
|
||||
:Returns:
|
||||
A :class:`~pymongo.change_stream.ClusterChangeStream` cursor.
|
||||
:return: A :class:`~pymongo.change_stream.ClusterChangeStream` cursor.
|
||||
|
||||
.. versionchanged:: 4.3
|
||||
Added `show_expanded_events` parameter.
|
||||
@ -1062,8 +1059,7 @@ class MongoClient(common.BaseObject, Generic[_DocumentType]):
|
||||
to get a more recent
|
||||
:class:`~pymongo.topology_description.TopologyDescription`.
|
||||
|
||||
:Returns:
|
||||
An instance of
|
||||
:return: An instance of
|
||||
:class:`~pymongo.topology_description.TopologyDescription`.
|
||||
|
||||
.. versionadded:: 4.0
|
||||
@ -1175,8 +1171,7 @@ class MongoClient(common.BaseObject, Generic[_DocumentType]):
|
||||
def options(self) -> ClientOptions:
|
||||
"""The configuration options for this client.
|
||||
|
||||
:Returns:
|
||||
An instance of :class:`~pymongo.client_options.ClientOptions`.
|
||||
:return: An instance of :class:`~pymongo.client_options.ClientOptions`.
|
||||
|
||||
.. versionadded:: 4.0
|
||||
"""
|
||||
@ -1281,12 +1276,11 @@ class MongoClient(common.BaseObject, Generic[_DocumentType]):
|
||||
) -> Server:
|
||||
"""Select a server to run an operation on this client.
|
||||
|
||||
:Parameters:
|
||||
- `server_selector`: The server selector to use if the session is
|
||||
:param server_selector: The server selector to use if the session is
|
||||
not pinned and no address is given.
|
||||
- `session`: The ClientSession for the next operation, or None. May
|
||||
:param session: The ClientSession for the next operation, or None. May
|
||||
be pinned to a mongos server address.
|
||||
- `address` (optional): Address when sending a message
|
||||
:param address: Address when sending a message
|
||||
to a specific server, used for getMore.
|
||||
"""
|
||||
try:
|
||||
@ -1361,10 +1355,9 @@ class MongoClient(common.BaseObject, Generic[_DocumentType]):
|
||||
) -> Response:
|
||||
"""Run a _Query/_GetMore operation and return a Response.
|
||||
|
||||
:Parameters:
|
||||
- `operation`: a _Query or _GetMore object.
|
||||
- `unpack_res`: A callable that decodes the wire protocol response.
|
||||
- `address` (optional): Optional address when sending a message
|
||||
:param operation: a _Query or _GetMore object.
|
||||
:param unpack_res: A callable that decodes the wire protocol response.
|
||||
:param address: Optional address when sending a message
|
||||
to a specific server, used for getMore.
|
||||
"""
|
||||
if operation.conn_mgr:
|
||||
@ -1441,17 +1434,15 @@ class MongoClient(common.BaseObject, Generic[_DocumentType]):
|
||||
) -> T:
|
||||
"""Internal retryable helper for all client transactions.
|
||||
|
||||
:Parameters:
|
||||
- `func`: Callback function we want to retry
|
||||
- `session`: Client Session on which the transaction should occur
|
||||
- `bulk`: Abstraction to handle bulk write operations
|
||||
- `is_read`: If this is an exclusive read transaction, defaults to False
|
||||
- `address`: Server Address, defaults to None
|
||||
- `read_pref`: Topology of read operation, defaults to None
|
||||
- `retryable`: If the operation should be retried once, defaults to None
|
||||
:param func: Callback function we want to retry
|
||||
:param session: Client Session on which the transaction should occur
|
||||
:param bulk: Abstraction to handle bulk write operations
|
||||
:param is_read: If this is an exclusive read transaction, defaults to False
|
||||
:param address: Server Address, defaults to None
|
||||
:param read_pref: Topology of read operation, defaults to None
|
||||
:param retryable: If the operation should be retried once, defaults to None
|
||||
|
||||
:Returns:
|
||||
Output of the calling func()
|
||||
:return: Output of the calling func()
|
||||
"""
|
||||
return _ClientConnectionRetryable(
|
||||
mongo_client=self,
|
||||
@ -1479,11 +1470,11 @@ class MongoClient(common.BaseObject, Generic[_DocumentType]):
|
||||
|
||||
Re-raises any exception thrown by func().
|
||||
|
||||
- `func`: Read call we want to execute
|
||||
- `read_pref`: Desired topology of read operation
|
||||
- `session`: Client session we should use to execute operation
|
||||
- `address`: Optional address when sending a message, defaults to None
|
||||
- `retryable`: if we should attempt retries
|
||||
:param func: Read call we want to execute
|
||||
:param read_pref: Desired topology of read operation
|
||||
:param session: Client session we should use to execute operation
|
||||
:param address: Optional address when sending a message, defaults to None
|
||||
:param retryable: if we should attempt retries
|
||||
(may not always be supported even if supplied), defaults to False
|
||||
"""
|
||||
|
||||
@ -1516,11 +1507,10 @@ class MongoClient(common.BaseObject, Generic[_DocumentType]):
|
||||
|
||||
Re-raises any exception thrown by func().
|
||||
|
||||
:Parameters:
|
||||
- `retryable`: if we should attempt retries (may not always be supported)
|
||||
- `func`: write call we want to execute during a session
|
||||
- `session`: Client session we will use to execute write operation
|
||||
- `bulk`: bulk abstraction to execute operations in bulk, defaults to None
|
||||
:param retryable: if we should attempt retries (may not always be supported)
|
||||
:param func: write call we want to execute during a session
|
||||
:param session: Client session we will use to execute write operation
|
||||
:param bulk: bulk abstraction to execute operations in bulk, defaults to None
|
||||
"""
|
||||
with self._tmp_session(session) as s:
|
||||
return self._retry_with_session(retryable, func, s, bulk)
|
||||
@ -1578,8 +1568,7 @@ class MongoClient(common.BaseObject, Generic[_DocumentType]):
|
||||
Raises :class:`~pymongo.errors.InvalidName` if an invalid
|
||||
database name is used.
|
||||
|
||||
:Parameters:
|
||||
- `name`: the name of the database to get
|
||||
:param name: the name of the database to get
|
||||
"""
|
||||
if name.startswith("_"):
|
||||
raise AttributeError(
|
||||
@ -1594,8 +1583,7 @@ class MongoClient(common.BaseObject, Generic[_DocumentType]):
|
||||
Raises :class:`~pymongo.errors.InvalidName` if an invalid
|
||||
database name is used.
|
||||
|
||||
:Parameters:
|
||||
- `name`: the name of the database to get
|
||||
:param name: the name of the database to get
|
||||
"""
|
||||
return database.Database(self, name)
|
||||
|
||||
@ -1614,13 +1602,12 @@ class MongoClient(common.BaseObject, Generic[_DocumentType]):
|
||||
pinned connection or implicit session attached at the time the cursor
|
||||
was closed or garbage collected.
|
||||
|
||||
:Parameters:
|
||||
- `locks_allowed`: True if we are allowed to acquire locks.
|
||||
- `cursor_id`: The cursor id which may be 0.
|
||||
- `address`: The _CursorAddress.
|
||||
- `conn_mgr`: The _ConnectionManager for the pinned connection or None.
|
||||
- `session`: The cursor's session.
|
||||
- `explicit_session`: True if the session was passed explicitly.
|
||||
:param locks_allowed: True if we are allowed to acquire locks.
|
||||
:param cursor_id: The cursor id which may be 0.
|
||||
:param address: The _CursorAddress.
|
||||
:param conn_mgr: The _ConnectionManager for the pinned connection or None.
|
||||
:param session: The cursor's session.
|
||||
:param explicit_session: True if the session was passed explicitly.
|
||||
"""
|
||||
if locks_allowed:
|
||||
if cursor_id:
|
||||
@ -1791,8 +1778,7 @@ class MongoClient(common.BaseObject, Generic[_DocumentType]):
|
||||
or process at a time. A single :class:`ClientSession` cannot be used
|
||||
to run multiple operations concurrently.
|
||||
|
||||
:Returns:
|
||||
An instance of :class:`~pymongo.client_session.ClientSession`.
|
||||
:return: An instance of :class:`~pymongo.client_session.ClientSession`.
|
||||
|
||||
.. versionadded:: 3.6
|
||||
"""
|
||||
@ -1881,8 +1867,7 @@ class MongoClient(common.BaseObject, Generic[_DocumentType]):
|
||||
def server_info(self, session: Optional[client_session.ClientSession] = None) -> dict[str, Any]:
|
||||
"""Get information about the MongoDB server we're connected to.
|
||||
|
||||
:Parameters:
|
||||
- `session` (optional): a
|
||||
:param session: a
|
||||
:class:`~pymongo.client_session.ClientSession`.
|
||||
|
||||
.. versionchanged:: 3.6
|
||||
@ -1903,20 +1888,18 @@ class MongoClient(common.BaseObject, Generic[_DocumentType]):
|
||||
) -> CommandCursor[dict[str, Any]]:
|
||||
"""Get a cursor over the databases of the connected server.
|
||||
|
||||
:Parameters:
|
||||
- `session` (optional): a
|
||||
:param session: a
|
||||
:class:`~pymongo.client_session.ClientSession`.
|
||||
- `comment` (optional): A user-provided comment to attach to this
|
||||
:param comment: A user-provided comment to attach to this
|
||||
command.
|
||||
- `**kwargs` (optional): Optional parameters of the
|
||||
:param kwargs: Optional parameters of the
|
||||
`listDatabases command
|
||||
<https://mongodb.com/docs/manual/reference/command/listDatabases/>`_
|
||||
can be passed as keyword arguments to this method. The supported
|
||||
options differ by server version.
|
||||
|
||||
|
||||
:Returns:
|
||||
An instance of :class:`~pymongo.command_cursor.CommandCursor`.
|
||||
:return: An instance of :class:`~pymongo.command_cursor.CommandCursor`.
|
||||
|
||||
.. versionadded:: 3.6
|
||||
"""
|
||||
@ -1941,10 +1924,9 @@ class MongoClient(common.BaseObject, Generic[_DocumentType]):
|
||||
) -> list[str]:
|
||||
"""Get a list of the names of all databases on the connected server.
|
||||
|
||||
:Parameters:
|
||||
- `session` (optional): a
|
||||
:param session: a
|
||||
:class:`~pymongo.client_session.ClientSession`.
|
||||
- `comment` (optional): A user-provided comment to attach to this
|
||||
:param comment: A user-provided comment to attach to this
|
||||
command.
|
||||
|
||||
.. versionchanged:: 4.1
|
||||
@ -1966,13 +1948,12 @@ class MongoClient(common.BaseObject, Generic[_DocumentType]):
|
||||
Raises :class:`TypeError` if `name_or_database` is not an instance of
|
||||
:class:`str` or :class:`~pymongo.database.Database`.
|
||||
|
||||
:Parameters:
|
||||
- `name_or_database`: the name of a database to drop, or a
|
||||
:param name_or_database: the name of a database to drop, or a
|
||||
:class:`~pymongo.database.Database` instance representing the
|
||||
database to drop
|
||||
- `session` (optional): a
|
||||
:param session: a
|
||||
:class:`~pymongo.client_session.ClientSession`.
|
||||
- `comment` (optional): A user-provided comment to attach to this
|
||||
:param comment: A user-provided comment to attach to this
|
||||
command.
|
||||
|
||||
.. versionchanged:: 4.1
|
||||
@ -2026,26 +2007,25 @@ class MongoClient(common.BaseObject, Generic[_DocumentType]):
|
||||
Useful in scripts where you want to choose which database to use
|
||||
based only on the URI in a configuration file.
|
||||
|
||||
:Parameters:
|
||||
- `default` (optional): the database name to use if no database name
|
||||
:param default: the database name to use if no database name
|
||||
was provided in the URI.
|
||||
- `codec_options` (optional): An instance of
|
||||
:param codec_options: An instance of
|
||||
:class:`~bson.codec_options.CodecOptions`. If ``None`` (the
|
||||
default) the :attr:`codec_options` of this :class:`MongoClient` is
|
||||
used.
|
||||
- `read_preference` (optional): The read preference to use. If
|
||||
:param read_preference: The read preference to use. If
|
||||
``None`` (the default) the :attr:`read_preference` of this
|
||||
:class:`MongoClient` is used. See :mod:`~pymongo.read_preferences`
|
||||
for options.
|
||||
- `write_concern` (optional): An instance of
|
||||
:param write_concern: An instance of
|
||||
:class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
|
||||
default) the :attr:`write_concern` of this :class:`MongoClient` is
|
||||
used.
|
||||
- `read_concern` (optional): An instance of
|
||||
:param read_concern: An instance of
|
||||
:class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the
|
||||
default) the :attr:`read_concern` of this :class:`MongoClient` is
|
||||
used.
|
||||
- `comment` (optional): A user-provided comment to attach to this
|
||||
:param comment: A user-provided comment to attach to this
|
||||
command.
|
||||
|
||||
.. versionchanged:: 4.1
|
||||
@ -2093,23 +2073,22 @@ class MongoClient(common.BaseObject, Generic[_DocumentType]):
|
||||
>>> db2.read_preference
|
||||
Secondary(tag_sets=None)
|
||||
|
||||
:Parameters:
|
||||
- `name` (optional): The name of the database - a string. If ``None``
|
||||
:param name: The name of the database - a string. If ``None``
|
||||
(the default) the database named in the MongoDB connection URI is
|
||||
returned.
|
||||
- `codec_options` (optional): An instance of
|
||||
:param codec_options: An instance of
|
||||
:class:`~bson.codec_options.CodecOptions`. If ``None`` (the
|
||||
default) the :attr:`codec_options` of this :class:`MongoClient` is
|
||||
used.
|
||||
- `read_preference` (optional): The read preference to use. If
|
||||
:param read_preference: The read preference to use. If
|
||||
``None`` (the default) the :attr:`read_preference` of this
|
||||
:class:`MongoClient` is used. See :mod:`~pymongo.read_preferences`
|
||||
for options.
|
||||
- `write_concern` (optional): An instance of
|
||||
:param write_concern: An instance of
|
||||
:class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
|
||||
default) the :attr:`write_concern` of this :class:`MongoClient` is
|
||||
used.
|
||||
- `read_concern` (optional): An instance of
|
||||
:param read_concern: An instance of
|
||||
:class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the
|
||||
default) the :attr:`read_concern` of this :class:`MongoClient` is
|
||||
used.
|
||||
@ -2299,11 +2278,9 @@ class _ClientConnectionRetryable(Generic[T]):
|
||||
def run(self) -> T:
|
||||
"""Runs the supplied func() and attempts a retry
|
||||
|
||||
:Raises:
|
||||
self._last_error: Last exception raised
|
||||
:raises: self._last_error: Last exception raised
|
||||
|
||||
:Returns:
|
||||
Result of the func() call
|
||||
:return: Result of the func() call
|
||||
"""
|
||||
# Increment the transaction id up front to ensure any retry attempt
|
||||
# will use the proper txnNumber, even if server or socket selection
|
||||
@ -2389,8 +2366,7 @@ class _ClientConnectionRetryable(Generic[T]):
|
||||
"""Checks if the ongoing client exchange experienced a exception previously.
|
||||
If so, raise last error
|
||||
|
||||
:Parameters:
|
||||
- `check_csot`: Checks CSOT to ensure we are retrying with time remaining defaults to False
|
||||
:param check_csot: Checks CSOT to ensure we are retrying with time remaining defaults to False
|
||||
"""
|
||||
if self._is_retrying():
|
||||
remaining = _csot.remaining()
|
||||
@ -2401,8 +2377,7 @@ class _ClientConnectionRetryable(Generic[T]):
|
||||
def _get_server(self) -> Server:
|
||||
"""Retrieves a server object based on provided object context
|
||||
|
||||
:Returns:
|
||||
Abstraction to connect to server
|
||||
:return: Abstraction to connect to server
|
||||
"""
|
||||
return self._client._select_server(
|
||||
self._server_selector,
|
||||
@ -2414,8 +2389,7 @@ class _ClientConnectionRetryable(Generic[T]):
|
||||
def _write(self) -> T:
|
||||
"""Wrapper method for write-type retryable client executions
|
||||
|
||||
:Returns:
|
||||
Output for func()'s call
|
||||
:return: Output for func()'s call
|
||||
"""
|
||||
try:
|
||||
max_wire_version = 0
|
||||
@ -2441,8 +2415,7 @@ class _ClientConnectionRetryable(Generic[T]):
|
||||
def _read(self) -> T:
|
||||
"""Wrapper method for read-type retryable client executions
|
||||
|
||||
:Returns:
|
||||
Output for func()'s call
|
||||
:return: Output for func()'s call
|
||||
"""
|
||||
self._server = self._get_server()
|
||||
assert self._read_pref is not None, "Read Preference required on read calls"
|
||||
|
||||
@ -229,24 +229,21 @@ class CommandListener(_EventListener):
|
||||
def started(self, event: CommandStartedEvent) -> None:
|
||||
"""Abstract method to handle a `CommandStartedEvent`.
|
||||
|
||||
:Parameters:
|
||||
- `event`: An instance of :class:`CommandStartedEvent`.
|
||||
:param event: An instance of :class:`CommandStartedEvent`.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def succeeded(self, event: CommandSucceededEvent) -> None:
|
||||
"""Abstract method to handle a `CommandSucceededEvent`.
|
||||
|
||||
:Parameters:
|
||||
- `event`: An instance of :class:`CommandSucceededEvent`.
|
||||
:param event: An instance of :class:`CommandSucceededEvent`.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def failed(self, event: CommandFailedEvent) -> None:
|
||||
"""Abstract method to handle a `CommandFailedEvent`.
|
||||
|
||||
:Parameters:
|
||||
- `event`: An instance of :class:`CommandFailedEvent`.
|
||||
:param event: An instance of :class:`CommandFailedEvent`.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@ -272,8 +269,7 @@ class ConnectionPoolListener(_EventListener):
|
||||
|
||||
Emitted when a connection Pool is created.
|
||||
|
||||
:Parameters:
|
||||
- `event`: An instance of :class:`PoolCreatedEvent`.
|
||||
:param event: An instance of :class:`PoolCreatedEvent`.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@ -282,8 +278,7 @@ class ConnectionPoolListener(_EventListener):
|
||||
|
||||
Emitted when a connection Pool is marked ready.
|
||||
|
||||
:Parameters:
|
||||
- `event`: An instance of :class:`PoolReadyEvent`.
|
||||
:param event: An instance of :class:`PoolReadyEvent`.
|
||||
|
||||
.. versionadded:: 4.0
|
||||
"""
|
||||
@ -294,8 +289,7 @@ class ConnectionPoolListener(_EventListener):
|
||||
|
||||
Emitted when a connection Pool is cleared.
|
||||
|
||||
:Parameters:
|
||||
- `event`: An instance of :class:`PoolClearedEvent`.
|
||||
:param event: An instance of :class:`PoolClearedEvent`.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@ -304,8 +298,7 @@ class ConnectionPoolListener(_EventListener):
|
||||
|
||||
Emitted when a connection Pool is closed.
|
||||
|
||||
:Parameters:
|
||||
- `event`: An instance of :class:`PoolClosedEvent`.
|
||||
:param event: An instance of :class:`PoolClosedEvent`.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@ -314,8 +307,7 @@ class ConnectionPoolListener(_EventListener):
|
||||
|
||||
Emitted when a connection Pool creates a Connection object.
|
||||
|
||||
:Parameters:
|
||||
- `event`: An instance of :class:`ConnectionCreatedEvent`.
|
||||
:param event: An instance of :class:`ConnectionCreatedEvent`.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@ -325,8 +317,7 @@ class ConnectionPoolListener(_EventListener):
|
||||
Emitted when a connection has finished its setup, and is now ready to
|
||||
use.
|
||||
|
||||
:Parameters:
|
||||
- `event`: An instance of :class:`ConnectionReadyEvent`.
|
||||
:param event: An instance of :class:`ConnectionReadyEvent`.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@ -335,8 +326,7 @@ class ConnectionPoolListener(_EventListener):
|
||||
|
||||
Emitted when a connection Pool closes a connection.
|
||||
|
||||
:Parameters:
|
||||
- `event`: An instance of :class:`ConnectionClosedEvent`.
|
||||
:param event: An instance of :class:`ConnectionClosedEvent`.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@ -345,8 +335,7 @@ class ConnectionPoolListener(_EventListener):
|
||||
|
||||
Emitted when the driver starts attempting to check out a connection.
|
||||
|
||||
:Parameters:
|
||||
- `event`: An instance of :class:`ConnectionCheckOutStartedEvent`.
|
||||
:param event: An instance of :class:`ConnectionCheckOutStartedEvent`.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@ -355,8 +344,7 @@ class ConnectionPoolListener(_EventListener):
|
||||
|
||||
Emitted when the driver's attempt to check out a connection fails.
|
||||
|
||||
:Parameters:
|
||||
- `event`: An instance of :class:`ConnectionCheckOutFailedEvent`.
|
||||
:param event: An instance of :class:`ConnectionCheckOutFailedEvent`.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@ -365,8 +353,7 @@ class ConnectionPoolListener(_EventListener):
|
||||
|
||||
Emitted when the driver successfully checks out a connection.
|
||||
|
||||
:Parameters:
|
||||
- `event`: An instance of :class:`ConnectionCheckedOutEvent`.
|
||||
:param event: An instance of :class:`ConnectionCheckedOutEvent`.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@ -376,8 +363,7 @@ class ConnectionPoolListener(_EventListener):
|
||||
Emitted when the driver checks in a connection back to the connection
|
||||
Pool.
|
||||
|
||||
:Parameters:
|
||||
- `event`: An instance of :class:`ConnectionCheckedInEvent`.
|
||||
:param event: An instance of :class:`ConnectionCheckedInEvent`.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@ -394,24 +380,21 @@ class ServerHeartbeatListener(_EventListener):
|
||||
def started(self, event: ServerHeartbeatStartedEvent) -> None:
|
||||
"""Abstract method to handle a `ServerHeartbeatStartedEvent`.
|
||||
|
||||
:Parameters:
|
||||
- `event`: An instance of :class:`ServerHeartbeatStartedEvent`.
|
||||
:param event: An instance of :class:`ServerHeartbeatStartedEvent`.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def succeeded(self, event: ServerHeartbeatSucceededEvent) -> None:
|
||||
"""Abstract method to handle a `ServerHeartbeatSucceededEvent`.
|
||||
|
||||
:Parameters:
|
||||
- `event`: An instance of :class:`ServerHeartbeatSucceededEvent`.
|
||||
:param event: An instance of :class:`ServerHeartbeatSucceededEvent`.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def failed(self, event: ServerHeartbeatFailedEvent) -> None:
|
||||
"""Abstract method to handle a `ServerHeartbeatFailedEvent`.
|
||||
|
||||
:Parameters:
|
||||
- `event`: An instance of :class:`ServerHeartbeatFailedEvent`.
|
||||
:param event: An instance of :class:`ServerHeartbeatFailedEvent`.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@ -427,24 +410,21 @@ class TopologyListener(_EventListener):
|
||||
def opened(self, event: TopologyOpenedEvent) -> None:
|
||||
"""Abstract method to handle a `TopologyOpenedEvent`.
|
||||
|
||||
:Parameters:
|
||||
- `event`: An instance of :class:`TopologyOpenedEvent`.
|
||||
:param event: An instance of :class:`TopologyOpenedEvent`.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def description_changed(self, event: TopologyDescriptionChangedEvent) -> None:
|
||||
"""Abstract method to handle a `TopologyDescriptionChangedEvent`.
|
||||
|
||||
:Parameters:
|
||||
- `event`: An instance of :class:`TopologyDescriptionChangedEvent`.
|
||||
:param event: An instance of :class:`TopologyDescriptionChangedEvent`.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def closed(self, event: TopologyClosedEvent) -> None:
|
||||
"""Abstract method to handle a `TopologyClosedEvent`.
|
||||
|
||||
:Parameters:
|
||||
- `event`: An instance of :class:`TopologyClosedEvent`.
|
||||
:param event: An instance of :class:`TopologyClosedEvent`.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@ -460,24 +440,21 @@ class ServerListener(_EventListener):
|
||||
def opened(self, event: ServerOpeningEvent) -> None:
|
||||
"""Abstract method to handle a `ServerOpeningEvent`.
|
||||
|
||||
:Parameters:
|
||||
- `event`: An instance of :class:`ServerOpeningEvent`.
|
||||
:param event: An instance of :class:`ServerOpeningEvent`.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def description_changed(self, event: ServerDescriptionChangedEvent) -> None:
|
||||
"""Abstract method to handle a `ServerDescriptionChangedEvent`.
|
||||
|
||||
:Parameters:
|
||||
- `event`: An instance of :class:`ServerDescriptionChangedEvent`.
|
||||
:param event: An instance of :class:`ServerDescriptionChangedEvent`.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def closed(self, event: ServerClosedEvent) -> None:
|
||||
"""Abstract method to handle a `ServerClosedEvent`.
|
||||
|
||||
:Parameters:
|
||||
- `event`: An instance of :class:`ServerClosedEvent`.
|
||||
:param event: An instance of :class:`ServerClosedEvent`.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@ -507,8 +484,7 @@ def _validate_event_listeners(
|
||||
def register(listener: _EventListener) -> None:
|
||||
"""Register a global event listener.
|
||||
|
||||
:Parameters:
|
||||
- `listener`: A subclasses of :class:`CommandListener`,
|
||||
:param listener: A subclasses of :class:`CommandListener`,
|
||||
:class:`ServerHeartbeatListener`, :class:`ServerListener`,
|
||||
:class:`TopologyListener`, or :class:`ConnectionPoolListener`.
|
||||
"""
|
||||
@ -619,14 +595,13 @@ class _CommandEvent:
|
||||
class CommandStartedEvent(_CommandEvent):
|
||||
"""Event published when a command starts.
|
||||
|
||||
:Parameters:
|
||||
- `command`: The command document.
|
||||
- `database_name`: The name of the database this command was run against.
|
||||
- `request_id`: The request id for this operation.
|
||||
- `connection_id`: The address (host, port) of the server this command
|
||||
:param command: The command document.
|
||||
:param database_name: The name of the database this command was run against.
|
||||
:param request_id: The request id for this operation.
|
||||
:param connection_id: The address (host, port) of the server this command
|
||||
was sent to.
|
||||
- `operation_id`: An optional identifier for a series of related events.
|
||||
- `service_id`: The service_id this command was sent to, or ``None``.
|
||||
:param operation_id: An optional identifier for a series of related events.
|
||||
:param service_id: The service_id this command was sent to, or ``None``.
|
||||
"""
|
||||
|
||||
__slots__ = ("__cmd",)
|
||||
@ -682,16 +657,15 @@ class CommandStartedEvent(_CommandEvent):
|
||||
class CommandSucceededEvent(_CommandEvent):
|
||||
"""Event published when a command succeeds.
|
||||
|
||||
:Parameters:
|
||||
- `duration`: The command duration as a datetime.timedelta.
|
||||
- `reply`: The server reply document.
|
||||
- `command_name`: The command name.
|
||||
- `request_id`: The request id for this operation.
|
||||
- `connection_id`: The address (host, port) of the server this command
|
||||
:param duration: The command duration as a datetime.timedelta.
|
||||
:param reply: The server reply document.
|
||||
:param command_name: The command name.
|
||||
:param request_id: The request id for this operation.
|
||||
:param connection_id: The address (host, port) of the server this command
|
||||
was sent to.
|
||||
- `operation_id`: An optional identifier for a series of related events.
|
||||
- `service_id`: The service_id this command was sent to, or ``None``.
|
||||
- `database_name`: The database this command was sent to, or ``""``.
|
||||
:param operation_id: An optional identifier for a series of related events.
|
||||
:param service_id: The service_id this command was sent to, or ``None``.
|
||||
:param database_name: The database this command was sent to, or ``""``.
|
||||
"""
|
||||
|
||||
__slots__ = ("__duration_micros", "__reply")
|
||||
@ -749,16 +723,15 @@ class CommandSucceededEvent(_CommandEvent):
|
||||
class CommandFailedEvent(_CommandEvent):
|
||||
"""Event published when a command fails.
|
||||
|
||||
:Parameters:
|
||||
- `duration`: The command duration as a datetime.timedelta.
|
||||
- `failure`: The server reply document.
|
||||
- `command_name`: The command name.
|
||||
- `request_id`: The request id for this operation.
|
||||
- `connection_id`: The address (host, port) of the server this command
|
||||
:param duration: The command duration as a datetime.timedelta.
|
||||
:param failure: The server reply document.
|
||||
:param command_name: The command name.
|
||||
:param request_id: The request id for this operation.
|
||||
:param connection_id: The address (host, port) of the server this command
|
||||
was sent to.
|
||||
- `operation_id`: An optional identifier for a series of related events.
|
||||
- `service_id`: The service_id this command was sent to, or ``None``.
|
||||
- `database_name`: The database this command was sent to, or ``""``.
|
||||
:param operation_id: An optional identifier for a series of related events.
|
||||
:param service_id: The service_id this command was sent to, or ``None``.
|
||||
:param database_name: The database this command was sent to, or ``""``.
|
||||
"""
|
||||
|
||||
__slots__ = ("__duration_micros", "__failure")
|
||||
@ -833,8 +806,7 @@ class _PoolEvent:
|
||||
class PoolCreatedEvent(_PoolEvent):
|
||||
"""Published when a Connection Pool is created.
|
||||
|
||||
:Parameters:
|
||||
- `address`: The address (host, port) pair of the server this Pool is
|
||||
:param address: The address (host, port) pair of the server this Pool is
|
||||
attempting to connect to.
|
||||
|
||||
.. versionadded:: 3.9
|
||||
@ -858,8 +830,7 @@ class PoolCreatedEvent(_PoolEvent):
|
||||
class PoolReadyEvent(_PoolEvent):
|
||||
"""Published when a Connection Pool is marked ready.
|
||||
|
||||
:Parameters:
|
||||
- `address`: The address (host, port) pair of the server this Pool is
|
||||
:param address: The address (host, port) pair of the server this Pool is
|
||||
attempting to connect to.
|
||||
|
||||
.. versionadded:: 4.0
|
||||
@ -871,10 +842,9 @@ class PoolReadyEvent(_PoolEvent):
|
||||
class PoolClearedEvent(_PoolEvent):
|
||||
"""Published when a Connection Pool is cleared.
|
||||
|
||||
:Parameters:
|
||||
- `address`: The address (host, port) pair of the server this Pool is
|
||||
:param address: The address (host, port) pair of the server this Pool is
|
||||
attempting to connect to.
|
||||
- `service_id`: The service_id this command was sent to, or ``None``.
|
||||
:param service_id: The service_id this command was sent to, or ``None``.
|
||||
|
||||
.. versionadded:: 3.9
|
||||
"""
|
||||
@ -902,8 +872,7 @@ class PoolClearedEvent(_PoolEvent):
|
||||
class PoolClosedEvent(_PoolEvent):
|
||||
"""Published when a Connection Pool is closed.
|
||||
|
||||
:Parameters:
|
||||
- `address`: The address (host, port) pair of the server this Pool is
|
||||
:param address: The address (host, port) pair of the server this Pool is
|
||||
attempting to connect to.
|
||||
|
||||
.. versionadded:: 3.9
|
||||
@ -995,10 +964,9 @@ class ConnectionCreatedEvent(_ConnectionIdEvent):
|
||||
NOTE: This connection is not ready for use until the
|
||||
:class:`ConnectionReadyEvent` is published.
|
||||
|
||||
:Parameters:
|
||||
- `address`: The address (host, port) pair of the server this
|
||||
:param address: The address (host, port) pair of the server this
|
||||
Connection is attempting to connect to.
|
||||
- `connection_id`: The integer ID of the Connection in this Pool.
|
||||
:param connection_id: The integer ID of the Connection in this Pool.
|
||||
|
||||
.. versionadded:: 3.9
|
||||
"""
|
||||
@ -1009,10 +977,9 @@ class ConnectionCreatedEvent(_ConnectionIdEvent):
|
||||
class ConnectionReadyEvent(_ConnectionIdEvent):
|
||||
"""Published when a Connection has finished its setup, and is ready to use.
|
||||
|
||||
:Parameters:
|
||||
- `address`: The address (host, port) pair of the server this
|
||||
:param address: The address (host, port) pair of the server this
|
||||
Connection is attempting to connect to.
|
||||
- `connection_id`: The integer ID of the Connection in this Pool.
|
||||
:param connection_id: The integer ID of the Connection in this Pool.
|
||||
|
||||
.. versionadded:: 3.9
|
||||
"""
|
||||
@ -1023,11 +990,10 @@ class ConnectionReadyEvent(_ConnectionIdEvent):
|
||||
class ConnectionClosedEvent(_ConnectionIdEvent):
|
||||
"""Published when a Connection is closed.
|
||||
|
||||
:Parameters:
|
||||
- `address`: The address (host, port) pair of the server this
|
||||
:param address: The address (host, port) pair of the server this
|
||||
Connection is attempting to connect to.
|
||||
- `connection_id`: The integer ID of the Connection in this Pool.
|
||||
- `reason`: A reason explaining why this connection was closed.
|
||||
:param connection_id: The integer ID of the Connection in this Pool.
|
||||
:param reason: A reason explaining why this connection was closed.
|
||||
|
||||
.. versionadded:: 3.9
|
||||
"""
|
||||
@ -1059,8 +1025,7 @@ class ConnectionClosedEvent(_ConnectionIdEvent):
|
||||
class ConnectionCheckOutStartedEvent(_ConnectionEvent):
|
||||
"""Published when the driver starts attempting to check out a connection.
|
||||
|
||||
:Parameters:
|
||||
- `address`: The address (host, port) pair of the server this
|
||||
:param address: The address (host, port) pair of the server this
|
||||
Connection is attempting to connect to.
|
||||
|
||||
.. versionadded:: 3.9
|
||||
@ -1072,10 +1037,9 @@ class ConnectionCheckOutStartedEvent(_ConnectionEvent):
|
||||
class ConnectionCheckOutFailedEvent(_ConnectionEvent):
|
||||
"""Published when the driver's attempt to check out a connection fails.
|
||||
|
||||
:Parameters:
|
||||
- `address`: The address (host, port) pair of the server this
|
||||
:param address: The address (host, port) pair of the server this
|
||||
Connection is attempting to connect to.
|
||||
- `reason`: A reason explaining why connection check out failed.
|
||||
:param reason: A reason explaining why connection check out failed.
|
||||
|
||||
.. versionadded:: 3.9
|
||||
"""
|
||||
@ -1102,10 +1066,9 @@ class ConnectionCheckOutFailedEvent(_ConnectionEvent):
|
||||
class ConnectionCheckedOutEvent(_ConnectionIdEvent):
|
||||
"""Published when the driver successfully checks out a connection.
|
||||
|
||||
:Parameters:
|
||||
- `address`: The address (host, port) pair of the server this
|
||||
:param address: The address (host, port) pair of the server this
|
||||
Connection is attempting to connect to.
|
||||
- `connection_id`: The integer ID of the Connection in this Pool.
|
||||
:param connection_id: The integer ID of the Connection in this Pool.
|
||||
|
||||
.. versionadded:: 3.9
|
||||
"""
|
||||
@ -1116,10 +1079,9 @@ class ConnectionCheckedOutEvent(_ConnectionIdEvent):
|
||||
class ConnectionCheckedInEvent(_ConnectionIdEvent):
|
||||
"""Published when the driver checks in a Connection into the Pool.
|
||||
|
||||
:Parameters:
|
||||
- `address`: The address (host, port) pair of the server this
|
||||
:param address: The address (host, port) pair of the server this
|
||||
Connection is attempting to connect to.
|
||||
- `connection_id`: The integer ID of the Connection in this Pool.
|
||||
:param connection_id: The integer ID of the Connection in this Pool.
|
||||
|
||||
.. versionadded:: 3.9
|
||||
"""
|
||||
@ -1422,8 +1384,7 @@ class _EventListeners:
|
||||
|
||||
Any event listeners registered globally are included by default.
|
||||
|
||||
:Parameters:
|
||||
- `listeners`: A list of event listeners.
|
||||
:param listeners: A list of event listeners.
|
||||
"""
|
||||
|
||||
def __init__(self, listeners: Optional[Sequence[_EventListener]]):
|
||||
@ -1497,15 +1458,14 @@ class _EventListeners:
|
||||
) -> None:
|
||||
"""Publish a CommandStartedEvent to all command listeners.
|
||||
|
||||
:Parameters:
|
||||
- `command`: The command document.
|
||||
- `database_name`: The name of the database this command was run
|
||||
:param command: The command document.
|
||||
:param database_name: The name of the database this command was run
|
||||
against.
|
||||
- `request_id`: The request id for this operation.
|
||||
- `connection_id`: The address (host, port) of the server this
|
||||
:param request_id: The request id for this operation.
|
||||
:param connection_id: The address (host, port) of the server this
|
||||
command was sent to.
|
||||
- `op_id`: The (optional) operation id for this operation.
|
||||
- `service_id`: The service_id this command was sent to, or ``None``.
|
||||
:param op_id: The (optional) operation id for this operation.
|
||||
:param service_id: The service_id this command was sent to, or ``None``.
|
||||
"""
|
||||
if op_id is None:
|
||||
op_id = request_id
|
||||
@ -1532,17 +1492,16 @@ class _EventListeners:
|
||||
) -> None:
|
||||
"""Publish a CommandSucceededEvent to all command listeners.
|
||||
|
||||
:Parameters:
|
||||
- `duration`: The command duration as a datetime.timedelta.
|
||||
- `reply`: The server reply document.
|
||||
- `command_name`: The command name.
|
||||
- `request_id`: The request id for this operation.
|
||||
- `connection_id`: The address (host, port) of the server this
|
||||
:param duration: The command duration as a datetime.timedelta.
|
||||
:param reply: The server reply document.
|
||||
:param command_name: The command name.
|
||||
:param request_id: The request id for this operation.
|
||||
:param connection_id: The address (host, port) of the server this
|
||||
command was sent to.
|
||||
- `op_id`: The (optional) operation id for this operation.
|
||||
- `service_id`: The service_id this command was sent to, or ``None``.
|
||||
- `speculative_hello`: Was the command sent with speculative auth?
|
||||
- `database_name`: The database this command was sent to, or ``""``.
|
||||
:param op_id: The (optional) operation id for this operation.
|
||||
:param service_id: The service_id this command was sent to, or ``None``.
|
||||
:param speculative_hello: Was the command sent with speculative auth?
|
||||
:param database_name: The database this command was sent to, or ``""``.
|
||||
"""
|
||||
if op_id is None:
|
||||
op_id = request_id
|
||||
@ -1579,17 +1538,16 @@ class _EventListeners:
|
||||
) -> None:
|
||||
"""Publish a CommandFailedEvent to all command listeners.
|
||||
|
||||
:Parameters:
|
||||
- `duration`: The command duration as a datetime.timedelta.
|
||||
- `failure`: The server reply document or failure description
|
||||
:param duration: The command duration as a datetime.timedelta.
|
||||
:param failure: The server reply document or failure description
|
||||
document.
|
||||
- `command_name`: The command name.
|
||||
- `request_id`: The request id for this operation.
|
||||
- `connection_id`: The address (host, port) of the server this
|
||||
:param command_name: The command name.
|
||||
:param request_id: The request id for this operation.
|
||||
:param connection_id: The address (host, port) of the server this
|
||||
command was sent to.
|
||||
- `op_id`: The (optional) operation id for this operation.
|
||||
- `service_id`: The service_id this command was sent to, or ``None``.
|
||||
- `database_name`: The database this command was sent to, or ``""``.
|
||||
:param op_id: The (optional) operation id for this operation.
|
||||
:param service_id: The service_id this command was sent to, or ``None``.
|
||||
:param database_name: The database this command was sent to, or ``""``.
|
||||
"""
|
||||
if op_id is None:
|
||||
op_id = request_id
|
||||
@ -1613,9 +1571,8 @@ class _EventListeners:
|
||||
"""Publish a ServerHeartbeatStartedEvent to all server heartbeat
|
||||
listeners.
|
||||
|
||||
:Parameters:
|
||||
- `connection_id`: The address (host, port) pair of the connection.
|
||||
- `awaited`: True if this heartbeat is part of an awaitable hello command.
|
||||
:param connection_id: The address (host, port) pair of the connection.
|
||||
:param awaited: True if this heartbeat is part of an awaitable hello command.
|
||||
"""
|
||||
event = ServerHeartbeatStartedEvent(connection_id, awaited)
|
||||
for subscriber in self.__server_heartbeat_listeners:
|
||||
@ -1630,12 +1587,11 @@ class _EventListeners:
|
||||
"""Publish a ServerHeartbeatSucceededEvent to all server heartbeat
|
||||
listeners.
|
||||
|
||||
:Parameters:
|
||||
- `connection_id`: The address (host, port) pair of the connection.
|
||||
- `duration`: The execution time of the event in the highest possible
|
||||
:param connection_id: The address (host, port) pair of the connection.
|
||||
:param duration: The execution time of the event in the highest possible
|
||||
resolution for the platform.
|
||||
- `reply`: The command reply.
|
||||
- `awaited`: True if the response was awaited.
|
||||
:param reply: The command reply.
|
||||
:param awaited: True if the response was awaited.
|
||||
"""
|
||||
event = ServerHeartbeatSucceededEvent(duration, reply, connection_id, awaited)
|
||||
for subscriber in self.__server_heartbeat_listeners:
|
||||
@ -1650,12 +1606,11 @@ class _EventListeners:
|
||||
"""Publish a ServerHeartbeatFailedEvent to all server heartbeat
|
||||
listeners.
|
||||
|
||||
:Parameters:
|
||||
- `connection_id`: The address (host, port) pair of the connection.
|
||||
- `duration`: The execution time of the event in the highest possible
|
||||
:param connection_id: The address (host, port) pair of the connection.
|
||||
:param duration: The execution time of the event in the highest possible
|
||||
resolution for the platform.
|
||||
- `reply`: The command reply.
|
||||
- `awaited`: True if the response was awaited.
|
||||
:param reply: The command reply.
|
||||
:param awaited: True if the response was awaited.
|
||||
"""
|
||||
event = ServerHeartbeatFailedEvent(duration, reply, connection_id, awaited)
|
||||
for subscriber in self.__server_heartbeat_listeners:
|
||||
@ -1667,9 +1622,8 @@ class _EventListeners:
|
||||
def publish_server_opened(self, server_address: _Address, topology_id: ObjectId) -> None:
|
||||
"""Publish a ServerOpeningEvent to all server listeners.
|
||||
|
||||
:Parameters:
|
||||
- `server_address`: The address (host, port) pair of the server.
|
||||
- `topology_id`: A unique identifier for the topology this server
|
||||
:param server_address: The address (host, port) pair of the server.
|
||||
:param topology_id: A unique identifier for the topology this server
|
||||
is a part of.
|
||||
"""
|
||||
event = ServerOpeningEvent(server_address, topology_id)
|
||||
@ -1682,9 +1636,8 @@ class _EventListeners:
|
||||
def publish_server_closed(self, server_address: _Address, topology_id: ObjectId) -> None:
|
||||
"""Publish a ServerClosedEvent to all server listeners.
|
||||
|
||||
:Parameters:
|
||||
- `server_address`: The address (host, port) pair of the server.
|
||||
- `topology_id`: A unique identifier for the topology this server
|
||||
:param server_address: The address (host, port) pair of the server.
|
||||
:param topology_id: A unique identifier for the topology this server
|
||||
is a part of.
|
||||
"""
|
||||
event = ServerClosedEvent(server_address, topology_id)
|
||||
@ -1703,11 +1656,10 @@ class _EventListeners:
|
||||
) -> None:
|
||||
"""Publish a ServerDescriptionChangedEvent to all server listeners.
|
||||
|
||||
:Parameters:
|
||||
- `previous_description`: The previous server description.
|
||||
- `server_address`: The address (host, port) pair of the server.
|
||||
- `new_description`: The new server description.
|
||||
- `topology_id`: A unique identifier for the topology this server
|
||||
:param previous_description: The previous server description.
|
||||
:param server_address: The address (host, port) pair of the server.
|
||||
:param new_description: The new server description.
|
||||
:param topology_id: A unique identifier for the topology this server
|
||||
is a part of.
|
||||
"""
|
||||
event = ServerDescriptionChangedEvent(
|
||||
@ -1722,8 +1674,7 @@ class _EventListeners:
|
||||
def publish_topology_opened(self, topology_id: ObjectId) -> None:
|
||||
"""Publish a TopologyOpenedEvent to all topology listeners.
|
||||
|
||||
:Parameters:
|
||||
- `topology_id`: A unique identifier for the topology this server
|
||||
:param topology_id: A unique identifier for the topology this server
|
||||
is a part of.
|
||||
"""
|
||||
event = TopologyOpenedEvent(topology_id)
|
||||
@ -1736,8 +1687,7 @@ class _EventListeners:
|
||||
def publish_topology_closed(self, topology_id: ObjectId) -> None:
|
||||
"""Publish a TopologyClosedEvent to all topology listeners.
|
||||
|
||||
:Parameters:
|
||||
- `topology_id`: A unique identifier for the topology this server
|
||||
:param topology_id: A unique identifier for the topology this server
|
||||
is a part of.
|
||||
"""
|
||||
event = TopologyClosedEvent(topology_id)
|
||||
@ -1755,10 +1705,9 @@ class _EventListeners:
|
||||
) -> None:
|
||||
"""Publish a TopologyDescriptionChangedEvent to all topology listeners.
|
||||
|
||||
:Parameters:
|
||||
- `previous_description`: The previous topology description.
|
||||
- `new_description`: The new topology description.
|
||||
- `topology_id`: A unique identifier for the topology this server
|
||||
:param previous_description: The previous topology description.
|
||||
:param new_description: The new topology description.
|
||||
:param topology_id: A unique identifier for the topology this server
|
||||
is a part of.
|
||||
"""
|
||||
event = TopologyDescriptionChangedEvent(previous_description, new_description, topology_id)
|
||||
|
||||
@ -86,31 +86,30 @@ def command(
|
||||
) -> _DocumentType:
|
||||
"""Execute a command over the socket, or raise socket.error.
|
||||
|
||||
:Parameters:
|
||||
- `conn`: a Connection instance
|
||||
- `dbname`: name of the database on which to run the command
|
||||
- `spec`: a command document as an ordered dict type, eg SON.
|
||||
- `is_mongos`: are we connected to a mongos?
|
||||
- `read_preference`: a read preference
|
||||
- `codec_options`: a CodecOptions instance
|
||||
- `session`: optional ClientSession instance.
|
||||
- `client`: optional MongoClient instance for updating $clusterTime.
|
||||
- `check`: raise OperationFailure if there are errors
|
||||
- `allowable_errors`: errors to ignore if `check` is True
|
||||
- `address`: the (host, port) of `conn`
|
||||
- `listeners`: An instance of :class:`~pymongo.monitoring.EventListeners`
|
||||
- `max_bson_size`: The maximum encoded bson size for this server
|
||||
- `read_concern`: The read concern for this command.
|
||||
- `parse_write_concern_error`: Whether to parse the ``writeConcernError``
|
||||
:param conn: a Connection instance
|
||||
:param dbname: name of the database on which to run the command
|
||||
:param spec: a command document as an ordered dict type, eg SON.
|
||||
:param is_mongos: are we connected to a mongos?
|
||||
:param read_preference: a read preference
|
||||
:param codec_options: a CodecOptions instance
|
||||
:param session: optional ClientSession instance.
|
||||
:param client: optional MongoClient instance for updating $clusterTime.
|
||||
:param check: raise OperationFailure if there are errors
|
||||
:param allowable_errors: errors to ignore if `check` is True
|
||||
:param address: the (host, port) of `conn`
|
||||
:param listeners: An instance of :class:`~pymongo.monitoring.EventListeners`
|
||||
:param max_bson_size: The maximum encoded bson size for this server
|
||||
:param read_concern: The read concern for this command.
|
||||
:param parse_write_concern_error: Whether to parse the ``writeConcernError``
|
||||
field in the command response.
|
||||
- `collation`: The collation for this command.
|
||||
- `compression_ctx`: optional compression Context.
|
||||
- `use_op_msg`: True if we should use OP_MSG.
|
||||
- `unacknowledged`: True if this is an unacknowledged command.
|
||||
- `user_fields` (optional): Response fields that should be decoded
|
||||
:param collation: The collation for this command.
|
||||
:param compression_ctx: optional compression Context.
|
||||
:param use_op_msg: True if we should use OP_MSG.
|
||||
:param unacknowledged: True if this is an unacknowledged command.
|
||||
:param user_fields: Response fields that should be decoded
|
||||
using the TypeDecoders from codec_options, passed to
|
||||
bson._decode_all_selective.
|
||||
- `exhaust_allowed`: True if we should enable OP_MSG exhaustAllowed.
|
||||
:param exhaust_allowed: True if we should enable OP_MSG exhaustAllowed.
|
||||
"""
|
||||
name = next(iter(spec))
|
||||
ns = dbname + ".$cmd"
|
||||
|
||||
@ -55,8 +55,7 @@ class InsertOne(Generic[_DocumentType]):
|
||||
|
||||
For use with :meth:`~pymongo.collection.Collection.bulk_write`.
|
||||
|
||||
:Parameters:
|
||||
- `document`: The document to insert. If the document is missing an
|
||||
:param document: The document to insert. If the document is missing an
|
||||
_id field one will be added.
|
||||
"""
|
||||
self._doc = document
|
||||
@ -92,11 +91,10 @@ class DeleteOne:
|
||||
|
||||
For use with :meth:`~pymongo.collection.Collection.bulk_write`.
|
||||
|
||||
:Parameters:
|
||||
- `filter`: A query that matches the document to delete.
|
||||
- `collation` (optional): An instance of
|
||||
:param filter: A query that matches the document to delete.
|
||||
:param collation: An instance of
|
||||
:class:`~pymongo.collation.Collation`.
|
||||
- `hint` (optional): An index to use to support the query
|
||||
:param hint: An index to use to support the query
|
||||
predicate specified either by its string name, or in the same
|
||||
format as passed to
|
||||
:meth:`~pymongo.collection.Collection.create_index` (e.g.
|
||||
@ -157,11 +155,10 @@ class DeleteMany:
|
||||
|
||||
For use with :meth:`~pymongo.collection.Collection.bulk_write`.
|
||||
|
||||
:Parameters:
|
||||
- `filter`: A query that matches the documents to delete.
|
||||
- `collation` (optional): An instance of
|
||||
:param filter: A query that matches the documents to delete.
|
||||
:param collation: An instance of
|
||||
:class:`~pymongo.collation.Collation`.
|
||||
- `hint` (optional): An index to use to support the query
|
||||
:param hint: An index to use to support the query
|
||||
predicate specified either by its string name, or in the same
|
||||
format as passed to
|
||||
:meth:`~pymongo.collection.Collection.create_index` (e.g.
|
||||
@ -224,14 +221,13 @@ class ReplaceOne(Generic[_DocumentType]):
|
||||
|
||||
For use with :meth:`~pymongo.collection.Collection.bulk_write`.
|
||||
|
||||
:Parameters:
|
||||
- `filter`: A query that matches the document to replace.
|
||||
- `replacement`: The new document.
|
||||
- `upsert` (optional): If ``True``, perform an insert if no documents
|
||||
:param filter: A query that matches the document to replace.
|
||||
:param replacement: The new document.
|
||||
:param upsert: If ``True``, perform an insert if no documents
|
||||
match the filter.
|
||||
- `collation` (optional): An instance of
|
||||
:param collation: An instance of
|
||||
:class:`~pymongo.collation.Collation`.
|
||||
- `hint` (optional): An index to use to support the query
|
||||
:param hint: An index to use to support the query
|
||||
predicate specified either by its string name, or in the same
|
||||
format as passed to
|
||||
:meth:`~pymongo.collection.Collection.create_index` (e.g.
|
||||
@ -377,16 +373,15 @@ class UpdateOne(_UpdateOp):
|
||||
|
||||
For use with :meth:`~pymongo.collection.Collection.bulk_write`.
|
||||
|
||||
:Parameters:
|
||||
- `filter`: A query that matches the document to update.
|
||||
- `update`: The modifications to apply.
|
||||
- `upsert` (optional): If ``True``, perform an insert if no documents
|
||||
:param filter: A query that matches the document to update.
|
||||
:param update: The modifications to apply.
|
||||
:param upsert: If ``True``, perform an insert if no documents
|
||||
match the filter.
|
||||
- `collation` (optional): An instance of
|
||||
:param collation: An instance of
|
||||
:class:`~pymongo.collation.Collation`.
|
||||
- `array_filters` (optional): A list of filters specifying which
|
||||
:param array_filters: A list of filters specifying which
|
||||
array elements an update should apply.
|
||||
- `hint` (optional): An index to use to support the query
|
||||
:param hint: An index to use to support the query
|
||||
predicate specified either by its string name, or in the same
|
||||
format as passed to
|
||||
:meth:`~pymongo.collection.Collection.create_index` (e.g.
|
||||
@ -435,16 +430,15 @@ class UpdateMany(_UpdateOp):
|
||||
|
||||
For use with :meth:`~pymongo.collection.Collection.bulk_write`.
|
||||
|
||||
:Parameters:
|
||||
- `filter`: A query that matches the documents to update.
|
||||
- `update`: The modifications to apply.
|
||||
- `upsert` (optional): If ``True``, perform an insert if no documents
|
||||
:param filter: A query that matches the documents to update.
|
||||
:param update: The modifications to apply.
|
||||
:param upsert: If ``True``, perform an insert if no documents
|
||||
match the filter.
|
||||
- `collation` (optional): An instance of
|
||||
:param collation: An instance of
|
||||
:class:`~pymongo.collation.Collation`.
|
||||
- `array_filters` (optional): A list of filters specifying which
|
||||
:param array_filters: A list of filters specifying which
|
||||
array elements an update should apply.
|
||||
- `hint` (optional): An index to use to support the query
|
||||
:param hint: An index to use to support the query
|
||||
predicate specified either by its string name, or in the same
|
||||
format as passed to
|
||||
:meth:`~pymongo.collection.Collection.create_index` (e.g.
|
||||
@ -527,10 +521,9 @@ class IndexModel:
|
||||
See the MongoDB documentation for a full list of supported options by
|
||||
server version.
|
||||
|
||||
:Parameters:
|
||||
- `keys`: a single key or a list containing (key, direction) pairs
|
||||
:param keys: a single key or a list containing (key, direction) pairs
|
||||
or keys specifying the index to create.
|
||||
- `**kwargs` (optional): any additional index creation
|
||||
:param kwargs: any additional index creation
|
||||
options (see the above list) should be passed as keyword
|
||||
arguments.
|
||||
|
||||
@ -569,9 +562,8 @@ class SearchIndexModel:
|
||||
|
||||
For use with :meth:`~pymongo.collection.Collection.create_search_index` and :meth:`~pymongo.collection.Collection.create_search_indexes`.
|
||||
|
||||
:Parameters:
|
||||
- `definition` - The definition for this index.
|
||||
- `name` (optional) - The name for this index, if present.
|
||||
:param definition: - The definition for this index.
|
||||
:param name: - The name for this index, if present.
|
||||
|
||||
.. versionadded:: 4.5
|
||||
|
||||
|
||||
@ -36,12 +36,11 @@ class PeriodicExecutor:
|
||||
|
||||
If the target's return value is false, the executor stops.
|
||||
|
||||
:Parameters:
|
||||
- `interval`: Seconds between calls to `target`.
|
||||
- `min_interval`: Minimum seconds between calls if `wake` is
|
||||
:param interval: Seconds between calls to `target`.
|
||||
:param min_interval: Minimum seconds between calls if `wake` is
|
||||
called very often.
|
||||
- `target`: A function.
|
||||
- `name`: A name to give the underlying thread.
|
||||
:param target: A function.
|
||||
:param name: A name to give the underlying thread.
|
||||
"""
|
||||
# threading.Event and its internal condition variable are expensive
|
||||
# in Python 2, see PYTHON-983. Use a boolean to know when to wake.
|
||||
|
||||
@ -714,11 +714,10 @@ class _CancellationContext:
|
||||
class Connection:
|
||||
"""Store a connection with some metadata.
|
||||
|
||||
:Parameters:
|
||||
- `conn`: a raw connection object
|
||||
- `pool`: a Pool instance
|
||||
- `address`: the server's (host, port)
|
||||
- `id`: the id of this socket in it's pool
|
||||
:param conn: a raw connection object
|
||||
:param pool: a Pool instance
|
||||
:param address: the server's (host, port)
|
||||
:param id: the id of this socket in it's pool
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
@ -949,23 +948,22 @@ class Connection:
|
||||
) -> dict[str, Any]:
|
||||
"""Execute a command or raise an error.
|
||||
|
||||
:Parameters:
|
||||
- `dbname`: name of the database on which to run the command
|
||||
- `spec`: a command document as a dict, SON, or mapping object
|
||||
- `read_preference`: a read preference
|
||||
- `codec_options`: a CodecOptions instance
|
||||
- `check`: raise OperationFailure if there are errors
|
||||
- `allowable_errors`: errors to ignore if `check` is True
|
||||
- `read_concern`: The read concern for this command.
|
||||
- `write_concern`: The write concern for this command.
|
||||
- `parse_write_concern_error`: Whether to parse the
|
||||
:param dbname: name of the database on which to run the command
|
||||
:param spec: a command document as a dict, SON, or mapping object
|
||||
:param read_preference: a read preference
|
||||
:param codec_options: a CodecOptions instance
|
||||
:param check: raise OperationFailure if there are errors
|
||||
:param allowable_errors: errors to ignore if `check` is True
|
||||
:param read_concern: The read concern for this command.
|
||||
:param write_concern: The write concern for this command.
|
||||
:param parse_write_concern_error: Whether to parse the
|
||||
``writeConcernError`` field in the command response.
|
||||
- `collation`: The collation for this command.
|
||||
- `session`: optional ClientSession instance.
|
||||
- `client`: optional MongoClient for gossipping $clusterTime.
|
||||
- `retryable_write`: True if this command is a retryable write.
|
||||
- `publish_events`: Should we publish events for this command?
|
||||
- `user_fields` (optional): Response fields that should be decoded
|
||||
:param collation: The collation for this command.
|
||||
:param session: optional ClientSession instance.
|
||||
:param client: optional MongoClient for gossipping $clusterTime.
|
||||
:param retryable_write: True if this command is a retryable write.
|
||||
:param publish_events: Should we publish events for this command?
|
||||
:param user_fields: Response fields that should be decoded
|
||||
using the TypeDecoders from codec_options, passed to
|
||||
bson._decode_all_selective.
|
||||
"""
|
||||
@ -1057,9 +1055,8 @@ class Connection:
|
||||
|
||||
Can raise ConnectionFailure or InvalidDocument.
|
||||
|
||||
:Parameters:
|
||||
- `msg`: bytes, an OP_MSG message.
|
||||
- `max_doc_size`: size in bytes of the largest document in `msg`.
|
||||
:param msg: bytes, an OP_MSG message.
|
||||
:param max_doc_size: size in bytes of the largest document in `msg`.
|
||||
"""
|
||||
self._raise_if_not_writable(True)
|
||||
self.send_message(msg, max_doc_size)
|
||||
@ -1071,9 +1068,8 @@ class Connection:
|
||||
|
||||
Can raise ConnectionFailure or OperationFailure.
|
||||
|
||||
:Parameters:
|
||||
- `request_id`: an int.
|
||||
- `msg`: bytes, the command message.
|
||||
:param request_id: an int.
|
||||
:param msg: bytes, the command message.
|
||||
"""
|
||||
self.send_message(msg, 0)
|
||||
reply = self.receive_message(request_id)
|
||||
@ -1380,10 +1376,9 @@ class PoolState:
|
||||
class Pool:
|
||||
def __init__(self, address: _Address, options: PoolOptions, handshake: bool = True):
|
||||
"""
|
||||
:Parameters:
|
||||
- `address`: a (hostname, port) tuple
|
||||
- `options`: a PoolOptions instance
|
||||
- `handshake`: whether to call hello for each new Connection
|
||||
:param address: a (hostname, port) tuple
|
||||
:param options: a PoolOptions instance
|
||||
:param handshake: whether to call hello for each new Connection
|
||||
"""
|
||||
if options.pause_enabled:
|
||||
self.state = PoolState.PAUSED
|
||||
@ -1649,8 +1644,7 @@ class Pool:
|
||||
|
||||
Can raise ConnectionFailure or OperationFailure.
|
||||
|
||||
:Parameters:
|
||||
- `handler` (optional): A _MongoClientErrorHandler.
|
||||
:param handler: A _MongoClientErrorHandler.
|
||||
"""
|
||||
listeners = self.opts._event_listeners
|
||||
if self.enabled_for_cmap:
|
||||
@ -1804,8 +1798,7 @@ class Pool:
|
||||
def checkin(self, conn: Connection) -> None:
|
||||
"""Return the connection to the pool, or if it's closed discard it.
|
||||
|
||||
:Parameters:
|
||||
- `conn`: The connection to check into the pool.
|
||||
:param conn: The connection to check into the pool.
|
||||
"""
|
||||
txn = conn.pinned_txn
|
||||
cursor = conn.pinned_cursor
|
||||
|
||||
@ -21,8 +21,7 @@ from typing import Any, Optional
|
||||
class ReadConcern:
|
||||
"""ReadConcern
|
||||
|
||||
:Parameters:
|
||||
- `level`: (string) The read concern level specifies the level of
|
||||
:param level: (string) The read concern level specifies the level of
|
||||
isolation for read operations. For example, a read operation using a
|
||||
read concern level of ``majority`` will only return data that has been
|
||||
written to a majority of nodes. If the level is left unspecified, the
|
||||
|
||||
@ -301,15 +301,14 @@ class PrimaryPreferred(_ServerMode):
|
||||
created reads will be routed to an available secondary until the
|
||||
primary of the replica set is discovered.
|
||||
|
||||
:Parameters:
|
||||
- `tag_sets`: The :attr:`~tag_sets` to use if the primary is not
|
||||
:param tag_sets: The :attr:`~tag_sets` to use if the primary is not
|
||||
available.
|
||||
- `max_staleness`: (integer, in seconds) The maximum estimated
|
||||
:param max_staleness: (integer, in seconds) The maximum estimated
|
||||
length of time a replica set secondary can fall behind the primary in
|
||||
replication before it will no longer be selected for operations.
|
||||
Default -1, meaning no maximum. If it is set, it must be at least
|
||||
90 seconds.
|
||||
- `hedge`: The :attr:`~hedge` to use if the primary is not available.
|
||||
:param hedge: The :attr:`~hedge` to use if the primary is not available.
|
||||
|
||||
.. versionchanged:: 3.11
|
||||
Added ``hedge`` parameter.
|
||||
@ -345,14 +344,13 @@ class Secondary(_ServerMode):
|
||||
* When connected to a replica set queries are distributed among
|
||||
secondaries. An error is raised if no secondaries are available.
|
||||
|
||||
:Parameters:
|
||||
- `tag_sets`: The :attr:`~tag_sets` for this read preference.
|
||||
- `max_staleness`: (integer, in seconds) The maximum estimated
|
||||
:param tag_sets: The :attr:`~tag_sets` for this read preference.
|
||||
:param max_staleness: (integer, in seconds) The maximum estimated
|
||||
length of time a replica set secondary can fall behind the primary in
|
||||
replication before it will no longer be selected for operations.
|
||||
Default -1, meaning no maximum. If it is set, it must be at least
|
||||
90 seconds.
|
||||
- `hedge`: The :attr:`~hedge` for this read preference.
|
||||
:param hedge: The :attr:`~hedge` for this read preference.
|
||||
|
||||
.. versionchanged:: 3.11
|
||||
Added ``hedge`` parameter.
|
||||
@ -389,14 +387,13 @@ class SecondaryPreferred(_ServerMode):
|
||||
created reads will be routed to the primary of the replica set until
|
||||
an available secondary is discovered.
|
||||
|
||||
:Parameters:
|
||||
- `tag_sets`: The :attr:`~tag_sets` for this read preference.
|
||||
- `max_staleness`: (integer, in seconds) The maximum estimated
|
||||
:param tag_sets: The :attr:`~tag_sets` for this read preference.
|
||||
:param max_staleness: (integer, in seconds) The maximum estimated
|
||||
length of time a replica set secondary can fall behind the primary in
|
||||
replication before it will no longer be selected for operations.
|
||||
Default -1, meaning no maximum. If it is set, it must be at least
|
||||
90 seconds.
|
||||
- `hedge`: The :attr:`~hedge` for this read preference.
|
||||
:param hedge: The :attr:`~hedge` for this read preference.
|
||||
|
||||
.. versionchanged:: 3.11
|
||||
Added ``hedge`` parameter.
|
||||
@ -434,14 +431,13 @@ class Nearest(_ServerMode):
|
||||
* When connected to a replica set queries are distributed among all
|
||||
members.
|
||||
|
||||
:Parameters:
|
||||
- `tag_sets`: The :attr:`~tag_sets` for this read preference.
|
||||
- `max_staleness`: (integer, in seconds) The maximum estimated
|
||||
:param tag_sets: The :attr:`~tag_sets` for this read preference.
|
||||
:param max_staleness: (integer, in seconds) The maximum estimated
|
||||
length of time a replica set secondary can fall behind the primary in
|
||||
replication before it will no longer be selected for operations.
|
||||
Default -1, meaning no maximum. If it is set, it must be at least
|
||||
90 seconds.
|
||||
- `hedge`: The :attr:`~hedge` for this read preference.
|
||||
:param hedge: The :attr:`~hedge` for this read preference.
|
||||
|
||||
.. versionchanged:: 3.11
|
||||
Added ``hedge`` parameter.
|
||||
@ -471,8 +467,7 @@ class _AggWritePref:
|
||||
primary read preference.
|
||||
* Otherwise use `pref` read preference.
|
||||
|
||||
:Parameters:
|
||||
- `pref`: The read preference to use on MongoDB 5.0+.
|
||||
:param pref: The read preference to use on MongoDB 5.0+.
|
||||
"""
|
||||
|
||||
__slots__ = ("pref", "effective_pref")
|
||||
|
||||
@ -39,12 +39,11 @@ class Response:
|
||||
):
|
||||
"""Represent a response from the server.
|
||||
|
||||
:Parameters:
|
||||
- `data`: A network response message.
|
||||
- `address`: (host, port) of the source server.
|
||||
- `request_id`: The request id of this operation.
|
||||
- `duration`: The duration of the operation.
|
||||
- `from_command`: if the response is the result of a db command.
|
||||
:param data: A network response message.
|
||||
:param address: (host, port) of the source server.
|
||||
:param request_id: The request id of this operation.
|
||||
:param duration: The duration of the operation.
|
||||
:param from_command: if the response is the result of a db command.
|
||||
"""
|
||||
self._data = data
|
||||
self._address = address
|
||||
@ -100,15 +99,14 @@ class PinnedResponse(Response):
|
||||
):
|
||||
"""Represent a response to an exhaust cursor's initial query.
|
||||
|
||||
:Parameters:
|
||||
- `data`: A network response message.
|
||||
- `address`: (host, port) of the source server.
|
||||
- `conn`: The Connection used for the initial query.
|
||||
- `request_id`: The request id of this operation.
|
||||
- `duration`: The duration of the operation.
|
||||
- `from_command`: If the response is the result of a db command.
|
||||
- `docs`: List of documents.
|
||||
- `more_to_come`: Bool indicating whether cursor is ready to be
|
||||
:param data: A network response message.
|
||||
:param address: (host, port) of the source server.
|
||||
:param conn: The Connection used for the initial query.
|
||||
:param request_id: The request id of this operation.
|
||||
:param duration: The duration of the operation.
|
||||
:param from_command: If the response is the result of a db command.
|
||||
:param docs: List of documents.
|
||||
:param more_to_come: Bool indicating whether cursor is ready to be
|
||||
exhausted.
|
||||
"""
|
||||
super().__init__(data, address, request_id, duration, from_command, docs)
|
||||
|
||||
@ -187,9 +187,8 @@ class BulkWriteResult(_WriteResult):
|
||||
def __init__(self, bulk_api_result: dict[str, Any], acknowledged: bool) -> None:
|
||||
"""Create a BulkWriteResult instance.
|
||||
|
||||
:Parameters:
|
||||
- `bulk_api_result`: A result dict from the bulk API
|
||||
- `acknowledged`: Was this write result acknowledged? If ``False``
|
||||
:param bulk_api_result: A result dict from the bulk API
|
||||
:param acknowledged: Was this write result acknowledged? If ``False``
|
||||
then all properties of this object will raise
|
||||
:exc:`~pymongo.errors.InvalidOperation`.
|
||||
"""
|
||||
|
||||
@ -57,18 +57,16 @@ else:
|
||||
def saslprep(data: Any, prohibit_unassigned_code_points: Optional[bool] = True) -> Any:
|
||||
"""An implementation of RFC4013 SASLprep.
|
||||
|
||||
:Parameters:
|
||||
- `data`: The string to SASLprep. Unicode strings
|
||||
:param data: The string to SASLprep. Unicode strings
|
||||
(:class:`str`) are supported. Byte strings
|
||||
(:class:`bytes`) are ignored.
|
||||
- `prohibit_unassigned_code_points`: True / False. RFC 3454
|
||||
:param prohibit_unassigned_code_points: True / False. RFC 3454
|
||||
and RFCs for various SASL mechanisms distinguish between
|
||||
`queries` (unassigned code points allowed) and
|
||||
`stored strings` (unassigned code points prohibited). Defaults
|
||||
to ``True`` (unassigned code points are prohibited).
|
||||
|
||||
:Returns:
|
||||
The SASLprep'ed version of `data`.
|
||||
:return: The SASLprep'ed version of `data`.
|
||||
"""
|
||||
prohibited: Any
|
||||
|
||||
|
||||
@ -109,12 +109,11 @@ class Server:
|
||||
cursors.
|
||||
Can raise ConnectionFailure, OperationFailure, etc.
|
||||
|
||||
:Parameters:
|
||||
- `conn`: A Connection instance.
|
||||
- `operation`: A _Query or _GetMore object.
|
||||
- `read_preference`: The read preference to use.
|
||||
- `listeners`: Instance of _EventListeners or None.
|
||||
- `unpack_res`: A callable that decodes the wire protocol response.
|
||||
:param conn: A Connection instance.
|
||||
:param operation: A _Query or _GetMore object.
|
||||
:param read_preference: The read preference to use.
|
||||
:param listeners: Instance of _EventListeners or None.
|
||||
:param unpack_res: A callable that decodes the wire protocol response.
|
||||
"""
|
||||
duration = None
|
||||
assert listeners is not None
|
||||
@ -274,8 +273,7 @@ class Server:
|
||||
) -> tuple[int, Any, int]:
|
||||
"""Return request_id, data, max_doc_size.
|
||||
|
||||
:Parameters:
|
||||
- `message`: (request_id, data, max_doc_size) or (request_id, data)
|
||||
:param message: (request_id, data, max_doc_size) or (request_id, data)
|
||||
"""
|
||||
if len(message) == 3:
|
||||
return message # type: ignore[return-value]
|
||||
|
||||
@ -106,12 +106,11 @@ class ServerApi:
|
||||
):
|
||||
"""Options to configure MongoDB Stable API.
|
||||
|
||||
:Parameters:
|
||||
- `version`: The API version string. Must be one of the values in
|
||||
:param version: The API version string. Must be one of the values in
|
||||
:class:`ServerApiVersion`.
|
||||
- `strict` (optional): Set to ``True`` to enable API strict mode.
|
||||
:param strict: Set to ``True`` to enable API strict mode.
|
||||
Defaults to ``None`` which means "use the server's default".
|
||||
- `deprecation_errors` (optional): Set to ``True`` to enable
|
||||
:param deprecation_errors: Set to ``True`` to enable
|
||||
deprecation errors. Defaults to ``None`` which means "use the
|
||||
server's default".
|
||||
|
||||
@ -162,9 +161,8 @@ class ServerApi:
|
||||
def _add_to_command(cmd: MutableMapping[str, Any], server_api: Optional[ServerApi]) -> None:
|
||||
"""Internal helper which adds API versioning options to a command.
|
||||
|
||||
:Parameters:
|
||||
- `cmd`: The command.
|
||||
- `server_api` (optional): A :class:`ServerApi` or ``None``.
|
||||
:param cmd: The command.
|
||||
:param server_api: A :class:`ServerApi` or ``None``.
|
||||
"""
|
||||
if not server_api:
|
||||
return
|
||||
|
||||
@ -29,12 +29,11 @@ from pymongo.typings import ClusterTime, _Address
|
||||
class ServerDescription:
|
||||
"""Immutable representation of one server.
|
||||
|
||||
:Parameters:
|
||||
- `address`: A (host, port) pair
|
||||
- `hello`: Optional Hello instance
|
||||
- `round_trip_time`: Optional float
|
||||
- `error`: Optional, the last error attempting to connect to the server
|
||||
- `round_trip_time`: Optional float, the min latency from the most recent samples
|
||||
:param address: A (host, port) pair
|
||||
:param hello: Optional Hello instance
|
||||
:param round_trip_time: Optional float
|
||||
:param error: Optional, the last error attempting to connect to the server
|
||||
:param round_trip_time: Optional float, the min latency from the most recent samples
|
||||
"""
|
||||
|
||||
__slots__ = (
|
||||
|
||||
@ -215,13 +215,12 @@ class Topology:
|
||||
) -> list[Server]:
|
||||
"""Return a list of Servers matching selector, or time out.
|
||||
|
||||
:Parameters:
|
||||
- `selector`: function that takes a list of Servers and returns
|
||||
:param selector: function that takes a list of Servers and returns
|
||||
a subset of them.
|
||||
- `server_selection_timeout` (optional): maximum seconds to wait.
|
||||
:param server_selection_timeout: maximum seconds to wait.
|
||||
If not provided, the default value common.SERVER_SELECTION_TIMEOUT
|
||||
is used.
|
||||
- `address`: optional server address to select.
|
||||
:param address: optional server address to select.
|
||||
|
||||
Calls self.open() if needed.
|
||||
|
||||
@ -318,9 +317,8 @@ class Topology:
|
||||
servers. Time out after "server_selection_timeout" if the server
|
||||
cannot be reached.
|
||||
|
||||
:Parameters:
|
||||
- `address`: A (host, port) pair.
|
||||
- `server_selection_timeout` (optional): maximum seconds to wait.
|
||||
:param address: A (host, port) pair.
|
||||
:param server_selection_timeout: maximum seconds to wait.
|
||||
If not provided, the default value
|
||||
common.SERVER_SELECTION_TIMEOUT is used.
|
||||
|
||||
|
||||
@ -69,14 +69,13 @@ class TopologyDescription:
|
||||
) -> None:
|
||||
"""Representation of a deployment of MongoDB servers.
|
||||
|
||||
:Parameters:
|
||||
- `topology_type`: initial type
|
||||
- `server_descriptions`: dict of (address, ServerDescription) for
|
||||
:param topology_type: initial type
|
||||
:param server_descriptions: dict of (address, ServerDescription) for
|
||||
all seeds
|
||||
- `replica_set_name`: replica set name or None
|
||||
- `max_set_version`: greatest setVersion seen from a primary, or None
|
||||
- `max_election_id`: greatest electionId seen from a primary, or None
|
||||
- `topology_settings`: a TopologySettings
|
||||
:param replica_set_name: replica set name or None
|
||||
:param max_set_version: greatest setVersion seen from a primary, or None
|
||||
:param max_election_id: greatest electionId seen from a primary, or None
|
||||
:param topology_settings: a TopologySettings
|
||||
"""
|
||||
self._topology_type = topology_type
|
||||
self._replica_set_name = replica_set_name
|
||||
@ -283,12 +282,11 @@ class TopologyDescription:
|
||||
) -> list[ServerDescription]:
|
||||
"""List of servers matching the provided selector(s).
|
||||
|
||||
:Parameters:
|
||||
- `selector`: a callable that takes a Selection as input and returns
|
||||
:param selector: a callable that takes a Selection as input and returns
|
||||
a Selection as output. For example, an instance of a read
|
||||
preference from :mod:`~pymongo.read_preferences`.
|
||||
- `address` (optional): A server address to select.
|
||||
- `custom_selector` (optional): A callable that augments server
|
||||
:param address: A server address to select.
|
||||
:param custom_selector: A callable that augments server
|
||||
selection rules. Accepts a list of
|
||||
:class:`~pymongo.server_description.ServerDescription` objects and
|
||||
return a list of server descriptions that should be considered
|
||||
@ -333,8 +331,7 @@ class TopologyDescription:
|
||||
"""Does this topology have any readable servers available matching the
|
||||
given read preference?
|
||||
|
||||
:Parameters:
|
||||
- `read_preference`: an instance of a read preference from
|
||||
:param read_preference: an instance of a read preference from
|
||||
:mod:`~pymongo.read_preferences`. Defaults to
|
||||
:attr:`~pymongo.read_preferences.ReadPreference.PRIMARY`.
|
||||
|
||||
@ -384,9 +381,8 @@ def updated_topology_description(
|
||||
) -> TopologyDescription:
|
||||
"""Return an updated copy of a TopologyDescription.
|
||||
|
||||
:Parameters:
|
||||
- `topology_description`: the current TopologyDescription
|
||||
- `server_description`: a new ServerDescription that resulted from
|
||||
:param topology_description: the current TopologyDescription
|
||||
:param server_description: a new ServerDescription that resulted from
|
||||
a hello call
|
||||
|
||||
Called after attempting (successfully or not) to call hello on the
|
||||
@ -489,9 +485,8 @@ def _updated_topology_description_srv_polling(
|
||||
) -> TopologyDescription:
|
||||
"""Return an updated copy of a TopologyDescription.
|
||||
|
||||
:Parameters:
|
||||
- `topology_description`: the current TopologyDescription
|
||||
- `seedlist`: a list of new seeds new ServerDescription that resulted from
|
||||
:param topology_description: the current TopologyDescription
|
||||
:param seedlist: a list of new seeds new ServerDescription that resulted from
|
||||
a hello call
|
||||
"""
|
||||
assert topology_description.topology_type in SRV_POLLING_TOPOLOGIES
|
||||
|
||||
@ -56,8 +56,7 @@ DEFAULT_PORT = 27017
|
||||
def _unquoted_percent(s: str) -> bool:
|
||||
"""Check for unescaped percent signs.
|
||||
|
||||
:Parameters:
|
||||
- `s`: A string. `s` can have things like '%25', '%2525',
|
||||
:param s: A string. `s` can have things like '%25', '%2525',
|
||||
and '%E2%85%A8' but cannot have unquoted percent like '%foo'.
|
||||
"""
|
||||
for i in range(len(s)):
|
||||
@ -78,8 +77,7 @@ def parse_userinfo(userinfo: str) -> tuple[str, str]:
|
||||
Returns a 2-tuple containing the unescaped username followed
|
||||
by the unescaped password.
|
||||
|
||||
:Parameters:
|
||||
- `userinfo`: A string of the form <username>:<password>
|
||||
:param userinfo: A string of the form <username>:<password>
|
||||
"""
|
||||
if "@" in userinfo or userinfo.count(":") > 1 or _unquoted_percent(userinfo):
|
||||
raise InvalidURI(
|
||||
@ -103,10 +101,9 @@ def parse_ipv6_literal_host(
|
||||
Returns a 2-tuple of IPv6 literal followed by port where
|
||||
port is default_port if it wasn't specified in entity.
|
||||
|
||||
:Parameters:
|
||||
- `entity`: A string that represents an IPv6 literal enclosed
|
||||
:param entity: A string that represents an IPv6 literal enclosed
|
||||
in braces (e.g. '[::1]' or '[::1]:27017').
|
||||
- `default_port`: The port number to use when one wasn't
|
||||
:param default_port: The port number to use when one wasn't
|
||||
specified in entity.
|
||||
"""
|
||||
if entity.find("]") == -1:
|
||||
@ -125,10 +122,9 @@ def parse_host(entity: str, default_port: Optional[int] = DEFAULT_PORT) -> _Addr
|
||||
Returns a 2-tuple of host followed by port where port is default_port
|
||||
if it wasn't specified in the string.
|
||||
|
||||
:Parameters:
|
||||
- `entity`: A host or host:port string where host could be a
|
||||
:param entity: A host or host:port string where host could be a
|
||||
hostname or IP address.
|
||||
- `default_port`: The port number to use when one wasn't
|
||||
:param default_port: The port number to use when one wasn't
|
||||
specified in entity.
|
||||
"""
|
||||
host = entity
|
||||
@ -192,8 +188,7 @@ def _handle_security_options(options: _CaseInsensitiveDictionary) -> _CaseInsens
|
||||
"""Raise appropriate errors when conflicting TLS options are present in
|
||||
the options dictionary.
|
||||
|
||||
:Parameters:
|
||||
- `options`: Instance of _CaseInsensitiveDictionary containing
|
||||
:param options: Instance of _CaseInsensitiveDictionary containing
|
||||
MongoDB URI options.
|
||||
"""
|
||||
# Implicitly defined options must not be explicitly specified.
|
||||
@ -247,8 +242,7 @@ def _handle_option_deprecations(options: _CaseInsensitiveDictionary) -> _CaseIns
|
||||
options dictionary. Removes deprecated option key, value pairs if the
|
||||
options dictionary is found to also have the renamed option.
|
||||
|
||||
:Parameters:
|
||||
- `options`: Instance of _CaseInsensitiveDictionary containing
|
||||
:param options: Instance of _CaseInsensitiveDictionary containing
|
||||
MongoDB URI options.
|
||||
"""
|
||||
for optname in list(options):
|
||||
@ -286,8 +280,7 @@ def _normalize_options(options: _CaseInsensitiveDictionary) -> _CaseInsensitiveD
|
||||
"""Normalizes option names in the options dictionary by converting them to
|
||||
their internally-used names.
|
||||
|
||||
:Parameters:
|
||||
- `options`: Instance of _CaseInsensitiveDictionary containing
|
||||
:param options: Instance of _CaseInsensitiveDictionary containing
|
||||
MongoDB URI options.
|
||||
"""
|
||||
# Expand the tlsInsecure option.
|
||||
@ -312,9 +305,8 @@ def validate_options(opts: Mapping[str, Any], warn: bool = False) -> MutableMapp
|
||||
False then errors will be thrown for invalid options, otherwise they will
|
||||
be ignored and a warning will be issued.
|
||||
|
||||
:Parameters:
|
||||
- `opts`: A dict of MongoDB URI options.
|
||||
- `warn` (optional): If ``True`` then warnings will be logged and
|
||||
:param opts: A dict of MongoDB URI options.
|
||||
:param warn: If ``True`` then warnings will be logged and
|
||||
invalid options will be ignored. Otherwise invalid options will
|
||||
cause errors.
|
||||
"""
|
||||
@ -327,13 +319,12 @@ def split_options(
|
||||
"""Takes the options portion of a MongoDB URI, validates each option
|
||||
and returns the options in a dictionary.
|
||||
|
||||
:Parameters:
|
||||
- `opt`: A string representing MongoDB URI options.
|
||||
- `validate`: If ``True`` (the default), validate and normalize all
|
||||
:param opt: A string representing MongoDB URI options.
|
||||
:param validate: If ``True`` (the default), validate and normalize all
|
||||
options.
|
||||
- `warn`: If ``False`` (the default), suppress all warnings raised
|
||||
:param warn: If ``False`` (the default), suppress all warnings raised
|
||||
during validation of options.
|
||||
- `normalize`: If ``True`` (the default), renames all options to their
|
||||
:param normalize: If ``True`` (the default), renames all options to their
|
||||
internally-used names.
|
||||
"""
|
||||
and_idx = opts.find("&")
|
||||
@ -375,9 +366,8 @@ def split_hosts(hosts: str, default_port: Optional[int] = DEFAULT_PORT) -> list[
|
||||
Returns a set of 2-tuples containing the host name (or IP) followed by
|
||||
port number.
|
||||
|
||||
:Parameters:
|
||||
- `hosts`: A string of the form host1[:port],host2[:port],...
|
||||
- `default_port`: The port number to use when one wasn't specified
|
||||
:param hosts: A string of the form host1[:port],host2[:port],...
|
||||
:param default_port: The port number to use when one wasn't specified
|
||||
for a host.
|
||||
"""
|
||||
nodes = []
|
||||
@ -442,21 +432,20 @@ def parse_uri(
|
||||
If the URI scheme is "mongodb+srv://" DNS SRV and TXT lookups will be done
|
||||
to build nodelist and options.
|
||||
|
||||
:Parameters:
|
||||
- `uri`: The MongoDB URI to parse.
|
||||
- `default_port`: The port number to use when one wasn't specified
|
||||
:param uri: The MongoDB URI to parse.
|
||||
:param default_port: The port number to use when one wasn't specified
|
||||
for a host in the URI.
|
||||
- `validate` (optional): If ``True`` (the default), validate and
|
||||
:param validate: If ``True`` (the default), validate and
|
||||
normalize all options. Default: ``True``.
|
||||
- `warn` (optional): When validating, if ``True`` then will warn
|
||||
:param warn: When validating, if ``True`` then will warn
|
||||
the user then ignore any invalid options or values. If ``False``,
|
||||
validation will error when options are unsupported or values are
|
||||
invalid. Default: ``False``.
|
||||
- `normalize` (optional): If ``True``, convert names of URI options
|
||||
:param normalize: If ``True``, convert names of URI options
|
||||
to their internally-used names. Default: ``True``.
|
||||
- `connect_timeout` (optional): The maximum time in milliseconds to
|
||||
:param connect_timeout: The maximum time in milliseconds to
|
||||
wait for a response from the DNS server.
|
||||
- `srv_service_name` (optional): A custom SRV service name
|
||||
:param srv_service_name: A custom SRV service name
|
||||
|
||||
.. versionchanged:: 4.6
|
||||
The delimiting slash (``/``) between hosts and connection options is now optional.
|
||||
|
||||
@ -31,23 +31,22 @@ def validate_boolean(option: str, value: Any) -> bool:
|
||||
class WriteConcern:
|
||||
"""WriteConcern
|
||||
|
||||
:Parameters:
|
||||
- `w`: (integer or string) Used with replication, write operations
|
||||
:param w: (integer or string) Used with replication, write operations
|
||||
will block until they have been replicated to the specified number
|
||||
or tagged set of servers. `w=<integer>` always includes the replica
|
||||
set primary (e.g. w=3 means write to the primary and wait until
|
||||
replicated to **two** secondaries). **w=0 disables acknowledgement
|
||||
of write operations and can not be used with other write concern
|
||||
options.**
|
||||
- `wtimeout`: (integer) Used in conjunction with `w`. Specify a value
|
||||
:param wtimeout: (integer) Used in conjunction with `w`. Specify a value
|
||||
in milliseconds to control how long to wait for write propagation
|
||||
to complete. If replication does not complete in the given
|
||||
timeframe, a timeout exception is raised.
|
||||
- `j`: If ``True`` block until write operations have been committed
|
||||
:param j: If ``True`` block until write operations have been committed
|
||||
to the journal. Cannot be used in combination with `fsync`. Write
|
||||
operations will fail with an exception if this option is used when
|
||||
the server is running without journaling.
|
||||
- `fsync`: If ``True`` and the server is running without journaling,
|
||||
:param fsync: If ``True`` and the server is running without journaling,
|
||||
blocks until the server has synced all data files to disk. If the
|
||||
server is running with journaling, this acts the same as the `j`
|
||||
option, blocking until write operations have been committed to the
|
||||
|
||||
@ -89,7 +89,7 @@ class TestComment(IntegrationTest):
|
||||
self.assertTrue(tested)
|
||||
if h not in [coll.aggregate_raw_batches]:
|
||||
self.assertIn(
|
||||
"`comment` (optional):",
|
||||
":param comment:",
|
||||
h.__doc__,
|
||||
)
|
||||
if h not in already_supported:
|
||||
|
||||
Loading…
Reference in New Issue
Block a user