+\h:dZddlmZddlZddlZddlZddlZddlZddlm Z ddl m Z m Z m Z mZmZmZmZmZmZmZmZmZmZmZmZmZmZddlmZmZmZddl m!Z!ddl"m#Z#m$Z$m%Z%m&Z&dd l'm(Z(dd l)m*Z*dd l+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7dd l8m9Z9m:Z:m;Z;dd lZ>m?Z?m@Z@mAZAddlBmCZCmDZDmEZEddlFmGZGmHZHddlImJZJmKZKmLZLmMZMmNZNmOZOmPZPddlQmRZRmSZSddlTmUZUddlVmWZWddlXmYZYddlZm[Z[ddl\m]Z]m^Z^m_Z_ddl`maZambZbddlcmdZdddlemfZfddlgmhZhddlimjZjddlkmlZlmmZmddlnmoZompZpddlqmrZrmsZsmtZtmuZumvZvmwZwddlxmyZymzZzm{Z{m|Z|m}Z}m~Z~mZdd lmZmZe rDdd!lmZdd"lmZdd#lmZdd$lmZdd%lXmZdd&lmZdd'lemZmZdd(lmZdd)lmZdd*lmZdd+lmZed,Ze ed-d.egefZe ed-d/d.eSgefZd0ZeeLeKeJeMeOeNfZGd1d2e$j<eeuZdd9Zd?d:Ze9rejLe;yy)@aTools for connecting to MongoDB. .. seealso:: :doc:`/examples/high_availability` for examples of connecting to replica sets or sets of mongos servers. To get a :class:`~pymongo.database.Database` instance from a :class:`MongoClient` use either dictionary-style or attribute-style access: .. doctest:: >>> from pymongo import MongoClient >>> c = MongoClient() >>> c.test_database Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), 'test_database') >>> c["test-database"] Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), 'test-database') ) annotationsN) defaultdict) TYPE_CHECKINGAnyCallable CollectionContextManager FrozenSet GeneratorGenericMappingMutableMappingNoReturnOptionalSequenceTypeTypeVarUnioncast)DEFAULT_CODEC_OPTIONS CodecOptions TypeRegistry) Timestamp)_csotcommonhelpers_sharedperiodic_executor) ClientOptions) DriverInfo) AutoReconnectBulkWriteErrorClientBulkWriteExceptionConfigurationErrorConnectionFailureInvalidOperationNotPrimaryErrorOperationFailure PyMongoErrorServerSelectionTimeoutErrorWaitQueueTimeoutErrorWriteConcernError)_HAS_REGISTER_AT_FORK _create_lock_release_locks)_CLIENT_LOGGER_COMMAND_LOGGER _debug_log_log_client_error _log_or_warn)_CursorAddress_GetMore_Query)ConnectionClosedReason_EventListeners) DeleteMany DeleteOne InsertOne ReplaceOne UpdateMany UpdateOne_Op)ReadPreference _ServerMode)ClientBulkWriteResult)ServerDescription)writable_server_selector) SERVER_TYPE)client_sessiondatabase uri_parser) ChangeStreamClusterChangeStream) _ClientBulk)_EmptyServerSession) CommandCursor)TopologySettings)Topology _ErrorContext) TOPOLOGY_TYPETopologyDescription) ClusterTime_Address _CollationIn _DocumentType_DocumentTypeArg _Pipeline) SRV_SCHEME_check_options_handle_option_deprecations_handle_security_options_normalize_options _validate_uri split_hosts)DEFAULT_WRITE_CONCERN WriteConcern) TracebackType)ObjectId) ReadConcern)Response) Selection)_Bulk) ClientSession_ServerSession)_ConnectionManager _Encrypter) Connection)ServerTrhrmrnTceZdZUdZdZdZejZde d< dN dOfd Z dPdZ dQd Z dRd Z dSd ZdPd ZdTdUd ZdVdZdWdZdPdZdXdZ dY dZdZed[dZed\dZed]dZd^dZd_dZd_dZd`dZdadZdadZdbdZ dbdZ!dPdZ" dT dcdZ#ddd Z$ de dfd!Z%dTdgd"Z& dhd#Z' di djd$Z( di dkd%Z)dld&Z*dmd'Z+dnd(Z,dZ-dod)Z.e.Z/dpd*Z0edqd+Z1edqd,Z2edrd-Z3edrd.Z4edsd/Z5edsd0Z6dtd1Z7dPd2Z8e9se8Z8dud3Z:e;jx dvd4Z= dw dxd5Z> dyd6Z?e;jx dzd7Z@ d{d8ZAeBj dT d|d9ZD dT d}d:ZEeBj d~ dd;ZF d dd<ZG d dd=ZH dd>ZI dd?ZJ d dd@ZK ddAZL ddBZMdPdCZNdPdDZO ddEZPe;jx d ddFZQddGZRdTddHZS d ddIZT d ddJZU d ddKZVeBj d ddLZWeBj d ddMZXxZYS) MongoClient localhostii)document_classtz_awareconnectzweakref.WeakValueDictionary_clientsNc |xst}||||||d||_| |j}t|tr|g}| |j }t|t stdt|||_ ||_ d|_ d|_ d|_ d|_|jdd} |jdd} |jdd} t!j"|} || d<d| i|_t'|_d } d}d}d}t!j"}d}| j+d }| j+d }t-|jDcgc] }d |vs| c}d kDr t/d|jD]}d |vrjt1||ddd |}|j3t4} |j(j7|d|dxs|}|dxs|}|dxs|}|d}|d}q|j(j7t9||j|j(s t/d|j(Dcgc]}|d c}D]}t;|sn||| d<||j+dd }|ddlm}|j+d| }|| d<|| d<|jA| |}| |j+dt jB}|xs|j+d }|jE||j(}|j+d|}|j+d|}tG||||tH|_%||_&tO|_(g|_)d|_*|j$j7| ||||j(||| | | d tV||jJjZ|jJj\|jJj^|jJj`|jc|j(||d |_2d |_3d|_4| s|jktHr|r|jmyyycc}wcc}w)axyClient for a MongoDB instance, a replica set, or a set of mongoses. .. warning:: Starting in PyMongo 4.0, ``directConnection`` now has a default value of False instead of None. For more details, see the relevant section of the PyMongo 4.x migration guide: :ref:`pymongo4-migration-direct-connection`. The client object is thread-safe and has connection-pooling built in. If an operation fails because of a network error, :class:`~pymongo.errors.ConnectionFailure` is raised and the client reconnects in the background. Application code should handle this exception (recognizing that the operation failed) and then continue to execute. The `host` parameter can be a full `mongodb URI `_, in addition to a simple hostname. It can also be a list of hostnames but no more than one URI. Any port specified in the host string(s) will override the `port` parameter. For username and passwords reserved characters like ':', '/', '+' and '@' must be percent encoded following RFC 2396:: from urllib.parse import quote_plus uri = "mongodb://%s:%s@%s" % ( quote_plus(user), quote_plus(password), host) client = MongoClient(uri) Unix domain sockets are also supported. The socket path must be percent encoded in the URI:: uri = "mongodb://%s:%s@%s" % ( quote_plus(user), quote_plus(password), quote_plus(socket_path)) client = MongoClient(uri) But not when passed as a simple hostname:: client = MongoClient('/tmp/mongodb-27017.sock') Starting with version 3.6, PyMongo supports mongodb+srv:// URIs. The URI must include one, and only one, hostname. The hostname will be resolved to one or more DNS `SRV records `_ which will be used as the seed list for connecting to the MongoDB deployment. When using SRV URIs, the `authSource` and `replicaSet` configuration options can be specified using `TXT records `_. See the `Initial DNS Seedlist Discovery spec `_ for more details. Note that the use of SRV URIs implicitly enables TLS support. Pass tls=false in the URI to override. .. note:: MongoClient creation will block waiting for answers from DNS when mongodb+srv:// URIs are used. .. note:: Starting with version 3.0 the :class:`MongoClient` constructor no longer blocks while connecting to the server or servers, and it no longer raises :class:`~pymongo.errors.ConnectionFailure` if they are unavailable, nor :class:`~pymongo.errors.ConfigurationError` if the user's credentials are wrong. Instead, the constructor returns immediately and launches the connection process on background threads. You can check if the server is available like this:: from pymongo.errors import ConnectionFailure client = MongoClient() try: # The ping command is cheap and does not require auth. client.admin.command('ping') except ConnectionFailure: print("Server not available") .. warning:: When using PyMongo in a multiprocessing context, please read :ref:`multiprocessing` first. .. note:: Many of the following options can be passed using a MongoDB URI or keyword parameters. If the same option is passed in a URI and as a keyword parameter the keyword parameter takes precedence. :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. :param port: port number on which to connect :param document_class: default class to use for documents returned from queries on this client :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) :param connect: If ``True`` (the default), immediately begin connecting to MongoDB in the background. Otherwise connect on the first operation. The default value is ``False`` when running in a Function-as-a-service environment. :param type_registry: instance of :class:`~bson.codec_options.TypeRegistry` to enable encoding and decoding of custom types. :param kwargs: **Additional optional parameters available as keyword arguments:** - `datetime_conversion` (optional): 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 return DatetimeMS objects when the underlying datetime is 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. - `directConnection` (optional): if ``True``, forces this client to connect directly to the specified MongoDB host as a standalone. If ``false``, the client connects to the entire replica set of which the given MongoDB host(s) is a part. If this is ``True`` and a mongodb+srv:// URI or a URI containing multiple seeds is provided, an exception will be raised. - `maxPoolSize` (optional): The maximum allowable number of concurrent connections to each connected server. Requests to a server will block if there are `maxPoolSize` outstanding connections to the requested server. Defaults to 100. Can be either 0 or None, in which case there is no limit on the number of concurrent connections. - `minPoolSize` (optional): The minimum required number of concurrent connections that the pool will maintain to each connected server. Default is 0. - `maxIdleTimeMS` (optional): The maximum number of milliseconds that a connection can remain idle in the pool before being removed and replaced. Defaults to `None` (no limit). - `maxConnecting` (optional): The maximum number of connections that each pool can establish concurrently. Defaults to `2`. - `timeoutMS`: (integer or None) Controls how long (in milliseconds) the driver will wait when executing an operation (including retry attempts) before raising a timeout error. ``0`` or ``None`` means no timeout. - `socketTimeoutMS`: (integer or None) Controls how long (in milliseconds) the driver will wait for a response after sending an ordinary (non-monitoring) database operation before concluding that a network error has occurred. ``0`` or ``None`` means no timeout. Defaults to ``None`` (no timeout). - `connectTimeoutMS`: (integer or None) Controls how long (in milliseconds) the driver will wait during server monitoring when connecting a new socket to a server before concluding the server is unavailable. ``0`` or ``None`` means no timeout. Defaults to ``20000`` (20 seconds). - `server_selector`: (callable or None) Optional, user-provided function that augments server selection rules. The function should accept as an argument a list of :class:`~pymongo.server_description.ServerDescription` objects and return a list of server descriptions that should be considered suitable for the desired operation. - `serverSelectionTimeoutMS`: (integer) Controls how long (in milliseconds) the driver will wait to find an available, appropriate server to carry out a database operation; while it is waiting, multiple server monitoring operations may be carried out, each controlled by `connectTimeoutMS`. Defaults to ``30000`` (30 seconds). - `waitQueueTimeoutMS`: (integer or None) How long (in milliseconds) a thread will wait for a socket from the pool if the pool has no free sockets. Defaults to ``None`` (no timeout). - `heartbeatFrequencyMS`: (optional) The number of milliseconds between periodic server checks, or None to accept the default frequency of 10 seconds. - `serverMonitoringMode`: (optional) The server monitoring mode to use. Valid values are the strings: "auto", "stream", "poll". Defaults to "auto". - `appname`: (string or None) The name of the application that created this MongoClient instance. The server will log this value upon establishing each connection. It is also recorded in the slow query log and profile collections. - `driver`: (pair or None) A driver implemented on top of PyMongo can pass a :class:`~pymongo.driver_info.DriverInfo` to add its name, version, and platform to the message printed in the server log when establishing a connection. - `event_listeners`: a list or tuple of event listeners. See :mod:`~pymongo.monitoring` for details. - `retryWrites`: (boolean) Whether supported write operations executed within this MongoClient will be retried once after a network error. Defaults to ``True``. The supported write operations are: - :meth:`~pymongo.collection.Collection.bulk_write`, as long as :class:`~pymongo.operations.UpdateMany` or :class:`~pymongo.operations.DeleteMany` are not included. - :meth:`~pymongo.collection.Collection.delete_one` - :meth:`~pymongo.collection.Collection.insert_one` - :meth:`~pymongo.collection.Collection.insert_many` - :meth:`~pymongo.collection.Collection.replace_one` - :meth:`~pymongo.collection.Collection.update_one` - :meth:`~pymongo.collection.Collection.find_one_and_delete` - :meth:`~pymongo.collection.Collection.find_one_and_replace` - :meth:`~pymongo.collection.Collection.find_one_and_update` Unsupported write operations include, but are not limited to, :meth:`~pymongo.collection.Collection.aggregate` using the ``$out`` pipeline operator and any operation with an unacknowledged write concern (e.g. {w: 0})). See https://github.com/mongodb/specifications/blob/master/source/retryable-writes/retryable-writes.md - `retryReads`: (boolean) Whether supported read operations executed within this MongoClient will be retried once after a network error. Defaults to ``True``. The supported read operations are: :meth:`~pymongo.collection.Collection.find`, :meth:`~pymongo.collection.Collection.find_one`, :meth:`~pymongo.collection.Collection.aggregate` without ``$out``, :meth:`~pymongo.collection.Collection.distinct`, :meth:`~pymongo.collection.Collection.count`, :meth:`~pymongo.collection.Collection.estimated_document_count`, :meth:`~pymongo.collection.Collection.count_documents`, :meth:`pymongo.collection.Collection.watch`, :meth:`~pymongo.collection.Collection.list_indexes`, :meth:`pymongo.database.Database.watch`, :meth:`~pymongo.database.Database.list_collections`, :meth:`pymongo.mongo_client.MongoClient.watch`, and :meth:`~pymongo.mongo_client.MongoClient.list_databases`. Unsupported read operations include, but are not limited to :meth:`~pymongo.database.Database.command` and any getMore operation on a cursor. Enabling retryable reads makes applications more resilient to transient errors such as network failures, database upgrades, and replica set failovers. For an exact definition of which errors trigger a retry, see the `retryable reads specification `_. - `compressors`: Comma separated list of compressors for wire protocol compression. The list is used to negotiate a compressor with the server. Currently supported options are "snappy", "zlib" and "zstd". Support for snappy requires the `python-snappy `_ package. zlib support requires the Python standard library zlib module. zstd requires the `zstandard `_ package. By default no compression is used. Compression support must also be enabled on the server. MongoDB 3.6+ supports snappy and zlib compression. MongoDB 4.2+ adds support for zstd. See :ref:`network-compression-example` for details. - `zlibCompressionLevel`: (int) The zlib compression level to use when zlib is used as the wire protocol compressor. Supported values are -1 through 9. -1 tells the zlib library to use its default compression level (usually 6). 0 means no compression. 1 is best speed. 9 is best compression. Defaults to -1. - `uuidRepresentation`: The BSON representation to use when encoding from and decoding to instances of :class:`~uuid.UUID`. Valid values are the strings: "standard", "pythonLegacy", "javaLegacy", "csharpLegacy", and "unspecified" (the default). New applications should consider setting this to "standard" for cross language compatibility. See :ref:`handling-uuid-data-example` for details. - `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'. - `srvServiceName`: (string) The SRV service name to use for "mongodb+srv://" URIs. Defaults to "mongodb". Use it like so:: MongoClient("mongodb+srv://example.com/?srvServiceName=customname") - `srvMaxHosts`: (int) limits the number of mongos-like hosts a client will connect to. More specifically, when a "mongodb+srv://" connection string resolves to more than srvMaxHosts number of hosts, the client will randomly choose an srvMaxHosts sized subset of hosts. | **Write Concern options:** | (Only set if passed. No default values.) - `w`: (integer or string) If this is a replica set, write operations will block until they have been replicated to the specified number or tagged set of servers. `w=` always includes the replica set primary (e.g. w=3 means write to the primary and wait until replicated to **two** secondaries). Passing w=0 **disables write acknowledgement** and all other write concern options. - `wTimeoutMS`: **DEPRECATED** (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. Passing wTimeoutMS=0 will cause **write operations to wait indefinitely**. - `journal`: 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, 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 journal. Cannot be used in combination with `j`. | **Replica set keyword arguments for connecting with a replica set - either directly or via a mongos:** - `replicaSet`: (string or None) The name of the replica set to connect to. The driver will verify that all servers it connects to match this name. Implies that the hosts specified are a seed list and the driver should attempt to find all members of the set. Defaults to ``None``. | **Read Preference:** - `readPreference`: The replica set read preference for this client. One of ``primary``, ``primaryPreferred``, ``secondary``, ``secondaryPreferred``, or ``nearest``. Defaults to ``primary``. - `readPreferenceTags`: Specifies a tag set as a comma-separated list of colon-separated key-value pairs. For example ``dc:ny,rack:1``. Defaults to ``None``. - `maxStalenessSeconds`: (integer) 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. Defaults to ``-1``, meaning no maximum. If maxStalenessSeconds is set, it must be a positive integer greater than or equal to 90 seconds. .. seealso:: :doc:`/examples/server_selection` | **Authentication:** - `username`: A string. - `password`: A string. Although username and password must be percent-escaped in a MongoDB URI, they must not be percent-escaped when passed as parameters. In this example, both the space and slash special characters are passed as-is:: MongoClient(username="user name", password="pass/word") - `authSource`: The database to authenticate on. Defaults to the database specified in the URI, if provided, or to "admin". - `authMechanism`: See :data:`~pymongo.auth.MECHANISMS` for options. If no mechanism is specified, PyMongo automatically negotiates the mechanism to use (SCRAM-SHA-1 or SCRAM-SHA-256) with the MongoDB server. - `authMechanismProperties`: Used to specify authentication mechanism specific options. To specify the service name for GSSAPI authentication pass authMechanismProperties='SERVICE_NAME:'. To specify the session token for MONGODB-AWS authentication pass ``authMechanismProperties='AWS_SESSION_TOKEN:'``. .. seealso:: :doc:`/examples/authentication` | **TLS/SSL configuration:** - `tls`: (boolean) If ``True``, create the connection to the server using transport layer security. Defaults to ``False``. - `tlsInsecure`: (boolean) Specify whether TLS constraints should be relaxed as much as possible. Setting ``tlsInsecure=True`` implies ``tlsAllowInvalidCertificates=True`` and ``tlsAllowInvalidHostnames=True``. Defaults to ``False``. Think very carefully before setting this to ``True`` as it dramatically reduces the security of TLS. - `tlsAllowInvalidCertificates`: (boolean) If ``True``, continues the TLS handshake regardless of the outcome of the certificate verification process. If this is ``False``, and a value is not provided for ``tlsCAFile``, PyMongo will attempt to load system provided CA certificates. If the python version in use does not support loading system CA certificates then the ``tlsCAFile`` parameter must point to a file of CA certificates. ``tlsAllowInvalidCertificates=False`` implies ``tls=True``. Defaults to ``False``. Think very carefully before setting this to ``True`` as that could make your application vulnerable to on-path attackers. - `tlsAllowInvalidHostnames`: (boolean) If ``True``, disables TLS hostname verification. ``tlsAllowInvalidHostnames=False`` implies ``tls=True``. Defaults to ``False``. Think very carefully before setting this to ``True`` as that could make your application vulnerable to on-path attackers. - `tlsCAFile`: A file containing a single or a bundle of "certification authority" certificates, which are used to validate certificates passed from the other end of the connection. Implies ``tls=True``. Defaults to ``None``. - `tlsCertificateKeyFile`: A file containing the client certificate and private key. Implies ``tls=True``. Defaults to ``None``. - `tlsCRLFile`: A file containing a PEM or DER formatted certificate revocation list. Implies ``tls=True``. Defaults to ``None``. - `tlsCertificateKeyFilePassword`: The password or passphrase for decrypting the private key in ``tlsCertificateKeyFile``. Only necessary if the private key is encrypted. Defaults to ``None``. - `tlsDisableOCSPEndpointCheck`: (boolean) If ``True``, disables certificate revocation status checking via the OCSP responder specified on the server certificate. ``tlsDisableOCSPEndpointCheck=False`` implies ``tls=True``. Defaults to ``False``. - `ssl`: (boolean) Alias for ``tls``. | **Read Concern options:** | (If not set explicitly, this will use the server default) - `readConcernLevel`: (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 server default will be used. | **Client side encryption options:** | (If not set explicitly, client side encryption will not be enabled.) - `auto_encryption_opts`: A :class:`~pymongo.encryption_options.AutoEncryptionOpts` which configures this client to automatically encrypt collection commands and automatically decrypt results. See :ref:`automatic-client-side-encryption` for an example. If a :class:`MongoClient` is configured with ``auto_encryption_opts`` and a non-None ``maxPoolSize``, a separate internal ``MongoClient`` is created if any of the following are true: - A ``key_vault_client`` is not passed to :class:`~pymongo.encryption_options.AutoEncryptionOpts` - ``bypass_auto_encrpytion=False`` is passed to :class:`~pymongo.encryption_options.AutoEncryptionOpts` | **Stable API options:** | (If not set explicitly, Stable API will not be enabled.) - `server_api`: A :class:`~pymongo.server_api.ServerApi` which configures this client to use Stable API. See :ref:`versioned-api-ref` for details. .. seealso:: The MongoDB documentation on `connections `_. .. versionchanged:: 4.5 Added the ``serverMonitoringMode`` keyword argument. .. versionchanged:: 4.2 Added the ``timeoutMS`` keyword argument. .. versionchanged:: 4.0 - Removed the fsync, unlock, is_locked, database_names, and close_cursor methods. See the :ref:`pymongo4-migration-guide`. - Removed the ``waitQueueMultiple`` and ``socketKeepAlive`` keyword arguments. - The default for `uuidRepresentation` was changed from ``pythonLegacy`` to ``unspecified``. - Added the ``srvServiceName``, ``maxConnecting``, and ``srvMaxHosts`` URI and keyword arguments. .. versionchanged:: 3.12 Added the ``server_api`` keyword argument. The following keyword arguments were deprecated: - ``ssl_certfile`` and ``ssl_keyfile`` were deprecated in favor of ``tlsCertificateKeyFile``. .. versionchanged:: 3.11 Added the following keyword arguments and URI options: - ``tlsDisableOCSPEndpointCheck`` - ``directConnection`` .. versionchanged:: 3.9 Added the ``retryReads`` keyword argument and URI option. Added the ``tlsInsecure`` keyword argument and URI option. The following keyword arguments and URI options were deprecated: - ``wTimeout`` was deprecated in favor of ``wTimeoutMS``. - ``j`` was deprecated in favor of ``journal``. - ``ssl_cert_reqs`` was deprecated in favor of ``tlsAllowInvalidCertificates``. - ``ssl_match_hostname`` was deprecated in favor of ``tlsAllowInvalidHostnames``. - ``ssl_ca_certs`` was deprecated in favor of ``tlsCAFile``. - ``ssl_certfile`` was deprecated in favor of ``tlsCertificateKeyFile``. - ``ssl_crlfile`` was deprecated in favor of ``tlsCRLFile``. - ``ssl_pem_passphrase`` was deprecated in favor of ``tlsCertificateKeyFilePassword``. .. versionchanged:: 3.9 ``retryWrites`` now defaults to ``True``. .. versionchanged:: 3.8 Added the ``server_selector`` keyword argument. Added the ``type_registry`` keyword argument. .. versionchanged:: 3.7 Added the ``driver`` keyword argument. .. versionchanged:: 3.6 Added support for mongodb+srv:// URIs. Added the ``retryWrites`` keyword argument and URI option. .. versionchanged:: 3.5 Add ``username`` and ``password`` options. Document the ``authSource``, ``authMechanism``, and ``authMechanismProperties`` options. Deprecated the ``socketKeepAlive`` keyword argument and URI option. ``socketKeepAlive`` now defaults to ``True``. .. versionchanged:: 3.0 :class:`~pymongo.mongo_client.MongoClient` is now the one and only client class for a standalone server, mongos, or replica set. It includes the functionality that had been split into :class:`~pymongo.mongo_client.MongoReplicaSetClient`: it can connect to a replica set, discover all its members, and monitor the set for stepdowns, elections, and reconfigs. The :class:`~pymongo.mongo_client.MongoClient` constructor no longer blocks while connecting to the server or servers, and it no longer raises :class:`~pymongo.errors.ConnectionFailure` if they are unavailable, nor :class:`~pymongo.errors.ConfigurationError` if the user's credentials are wrong. Instead, the constructor returns immediately and launches the connection process on background threads. Therefore the ``alive`` method is removed since it no longer provides meaningful information; even if the client is disconnected, it may discover a server in time to fulfill the next operation. In PyMongo 2.x, :class:`~pymongo.MongoClient` accepted a list of standalone MongoDB servers and used the first it could connect to:: MongoClient(['host1.com:27017', 'host2.com:27017']) A list of multiple standalones is no longer supported; if multiple servers are listed they must be members of the same replica set, or mongoses in the same sharded cluster. The behavior for a list of mongoses is changed from "high availability" to "load balancing". Before, the client connected to the lowest-latency mongos in the list, and used it until a network error prompted it to re-evaluate all mongoses' latencies and reconnect to one of them. In PyMongo 3, the client monitors its network latency to all the mongoses continuously, and distributes operations evenly among those with the lowest latency. See :ref:`mongos-load-balancing` for more information. The ``connect`` option is added. The ``start_request``, ``in_request``, and ``end_request`` methods are removed, as well as the ``auto_start_request`` option. The ``copy_database`` method is removed, see the :doc:`copy_database examples ` for alternatives. The :meth:`MongoClient.disconnect` method is removed; it was a synonym for :meth:`~pymongo.MongoClient.close`. :class:`~pymongo.mongo_client.MongoClient` no longer returns an instance of :class:`~pymongo.database.Database` for attribute names with leading underscores. You must use dict-style lookups instead:: client['__my_database__'] Not:: client.__my_database__ .. versionchanged:: 4.7 Deprecated parameter ``wTimeoutMS``, use :meth:`~pymongo.timeout`. .. versionchanged:: 4.9 The default value of ``connect`` is changed to ``False`` when running in a Function-as-a-service environment. )hostportrsrtru type_registryNz%port must be an instance of int, not _pool_class_monitor_class_condition_classrs keyword_optsFsrvservicename srvmaxhosts/z+host must not contain multiple MongoDB URIsT)validatewarn normalize srv_max_hostsnodelistusernamepasswordrGoptionsfqdn!need to specify at least one hostrrzrt_is_faasrusrvServiceName) is_srvrrdbaseseedsrsrv_service_name pool_class monitor_classcondition_class)7dict _init_kwargsHOST isinstancestrPORTint TypeErrortype_host_port _topology_timeout_topology_settings_event_listenerspopr_CaseInsensitiveDictionary_resolve_srv_infoset_seedsgetlenr#r^ startswithrYupdater__detect_external_dbpymongo.pool_optionsr _validate_kwargs_and_update_optsSRV_SERVICE_NAME_normalize_and_validate_optionsr_IS_SYNC_options_default_database_namer-_lock_kill_cursors_queue _encryptersuper__init__ codec_optionsread_preference write_concern read_concern_init_based_on_options_opened_closed_loop_init_background _get_topology)selfrxryrsrtrurzkwargs doc_classrrrr~rrrroptsrrrhentityresnodehostnamer __class__s c/root/niggaflix-v3/playground/venv/lib/python3.12/site-packages/pymongo/synchronous/mongo_client.pyrzMongoClient.__init__srn#*d ' * - -  <99D dC 6D <99D$$CDJ<PQ Q  #'&* 488<ZZ t4  #3T:  **%7>88@ )2 %&2@,1Oe 002'++,<=$((7 4::2a2 3a 7$%RS Sjj DFf}#!#"/  **:6 ""3z?3z?6hz?6hJ059~6{ "";vtzz#BC+ D,{{$%HI I-1[[9Ta9 H"8,   $,9L )  xx E2H ? 5hhyhj.9G#+ Z ") Y44\4H  ##xx(8&:Q:QR %@-)@ 33D$++F88J188J1%h%xP &+#!^ )+ 04 %% $$$4(!.#2    MM ' ' MM ) ) MM ' ' MM & &   ##DKK@PQ  :>   ! ! #      8{36:s Q)!Q) Q.c |jd}t}tj}|j d}|j d}|j D]}d|vry|j d}|%tj |jd|}tj||jddd|||}|j|d |d }n%|jt||j|s td |D cgc]} | d  c} D]} t| sn|d } |d} | |j d d} | d dlm} |j d| } | |d <| |d<|j#||}| |j dtj$}|xs|j d}|j'||}|j d|jd}|j d|jd}t)|||jd|t*|_|j/|||ycc} w)Nr~rrrconnecttimeoutmsTF)rrrconnect_timeoutrrrrrrrtrurrrrr)rrrrrr validate_timeout_or_none_or_zero cased_keyrH _parse_srvrrr_r#rrrrrrrrrr)rr~rrrrrtimeoutrrrrtrurrrs r _resolve_srvzMongoClient._resolve_srvws]--n= 002'++,<=$((7 jj= PFf}&**+=>&$EE$../ABGG!++JJ!#$+%5"/  S_-9~ [<=()LMM167T!W7 &x0  $J/H"9-G88J69((9(*n='/L $&-L #88tLD'#'88,U>U#V )DTXXm-DM77eDDxx D,B,B:,NOHxx D,B,B:,NOH)(D$:$:7$CT8DM  ' '}>N O{= P:8s Ic|jjj|_tdid|d|jjd|j dd|jjd|j dd|j dd|jj d|jjd |jjd |jjd |j d d |jjd |jjd|d|d|jjd|jr|jjnd|_ |jjr(ddlm}|||jj|_|jj&|_y)Nrreplica_set_namer pool_optionsrrlocal_threshold_msserver_selection_timeoutserver_selectorheartbeat_frequencyrdirect_connection load_balancedrrserver_monitoring_mode topology_idrrk)rrrrNrrrrrrrrrr _topology_idauto_encryption_optspymongo.synchronous.encryptionrlrrr)rrrrrls rrz"MongoClient._init_based_on_optionss!% : : K K"2# # !]];;# --l;# 33 # 00A # !223DE #  $}}??# &*]]%K%K# !MM99# !% A A# ''/# #mm==# --55# .# (# $(==#G#G!# "AE@W@W//<<]a## & == - - A(t}}/Q/QRDO -- cJt|}t|}t|||SN)r\r]rZ)rrrs rrz+MongoClient._normalize_and_validate_optionss'(-!$'ud# rcttjtfdj D|j |S)Nc3nK|],\}}tjj||.ywr)rrr).0kvr~s r z?MongoClient._validate_kwargs_and_update_opts..s+`41a!7!7!:A>`s25)r[rrritemsr)rr~rs ` rrz,MongoClient._validate_kwargs_and_update_optssI 3<@ 88 `.targets#ZF~  / / 7rpymongo_kill_cursors_thread)interval min_intervalrnameFreturnbool)rOrrr,rqrvr_pidrPeriodicExecutorrKILL_CURSOR_FREQUENCYMIN_HEARTBEAT_INTERVALweakrefrefclose_kill_cursors_executorr)rold_pidrexecutorrs @rrzMongoClient._init_backgrounds!$"9"9: AEK != 4.0. :param session: a :class:`~pymongo.client_session.ClientSession`. :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. :param comment: A user-provided comment to attach to this command. :param show_expanded_events: Include expanded events such as DDL events like `dropIndexes`. :return: A :class:`~pymongo.change_stream.ClusterChangeStream` cursor. .. versionchanged:: 4.3 Added `show_expanded_events` parameter. .. versionchanged:: 4.2 Added ``full_document_before_change`` parameter. .. versionchanged:: 4.1 Added ``comment`` parameter. .. versionchanged:: 3.9 Added the ``start_after`` parameter. .. versionadded:: 3.7 .. seealso:: The MongoDB documentation on `changeStreams `_. .. _change streams specification: https://github.com/mongodb/specifications/blob/master/source/change-streams/change-streams.md )show_expanded_events)rJadmin_initialize_cursor)rpipeline full_document resume_aftermax_await_time_ms batch_size collationstart_at_operation_timer start_aftercommentfull_document_before_changer change_streams rwatchzMongoClient.watch0sN`, JJ       #    '!5 ((*rc |jT|jDcic]\}}||ft||f}}}ttj |ddd|j S|jjScc}}w)aThe description of the connected MongoDB deployment. >>> client.topology_description , , ]> >>> client.topology_description.topology_type_name 'ReplicaSetWithPrimary' Note that the description is periodically updated in the background but the returned object itself is immutable. Access this property again to get a more recent :class:`~pymongo.topology_description.TopologyDescription`. :return: An instance of :class:`~pymongo.topology_description.TopologyDescription`. .. versionadded:: 4.0 N)rrrCrRrQUnknownr description)rrxryserverss rtopology_descriptionz MongoClient.topology_descriptions& >> !W[WbWbctd|%6d|%DDcGc&%%''  ~~)))dsA7c|j tS|jj}td|jDS)aSet of all currently connected servers. .. warning:: When connected to a replica set the value of :attr:`nodes` can change over time as :class:`MongoClient`'s view of the replica set changes. :attr:`nodes` can also be an empty set when :class:`MongoClient` is first instantiated and hasn't yet connected to any servers, or a network partition causes it to lose connection to all servers. c34K|]}|jywraddress)rss rrz$MongoClient.nodes..sFqFs)r frozensetr0 known_servers)rr0s rnodeszMongoClient.nodess< >> !; nn00 FK,E,EFFFrc|jS)zThe configuration options for this client. :return: An instance of :class:`~pymongo.client_options.ClientOptions`. .. versionadded:: 4.0 rrs rrzMongoClient.optionss}}rctt|jd|jj|jd|jdfS)Nrrr)tuplesortedrrrrs req_propszMongoClient.eq_propssN &//89 : MM * *  " "6 *  " "#5 6   rc|t||jr!|j|jk(StSr)rrr@NotImplementedrothers r__eq__zMongoClient.__eq__s. eT^^ ,==?enn&66 6rc||k( SrrrCs r__ne__zMongoClient.__ne__s5=  rc4t|jSr)hashr@rs r__hash__zMongoClient.__hash__sDMMO$$rcd djdjddg}n6djjDcgc]\}}|d||fzn|c}}zg}|j fdj D|j fdj j Dd j|Scc}}w) Nc|dk(r%|turyd|jd|jS|tjvr||dt |dzS|d|S)z9Fix options whose __repr__ isn't usable in a constructor.rszdocument_class=dictzdocument_class=.=i)r __module____name__rTIMEOUT_OPTIONSr)optionvalues r option_reprz-MongoClient._repr_helper..option_reprss))D=0,U-=-=,>a?OPP///E4E 3ut|#4"566XQui( (rzhost='mongodb+srv://r'zhost=%rz%s:%dc3^K|]$}|jj|&ywrr<rkeyrTrs rrz+MongoClient._repr_helper..s, >AKT]]33C8 9 s*-c3K|]E}|tjvr,|dk7r'|dk7r"|jj|Gyw)rrN)r_constructor_argsrrWs rrz+MongoClient._repr_helper..sR #d4455#:KPSWaPa T]]33C8 9 sA Az, )rRrrSrrr)rrrrextendrZrjoin)rrrxryrTs` @r _repr_helperzMongoClient._repr_helpers ) >> !-d.D.DV.L-MQOPG'+&=&=&C&C"d/3.>GtTl*DHG  EIE[E[    }}--  yy!!sCcTt|jd|jdS)N())rrPr]rs r__repr__zMongoClient.__repr__#s*t*%%&a(9(9(;'>rc |jdr*tt|jd|d|d|d|j |S)Get a database by name. Raises :class:`~pymongo.errors.InvalidName` if an invalid database name is used. :param name: the name of the database to get _z has no attribute z. To access the z database, use client[z].)rAttributeErrorrrP __getitem__rrs r __getattr__zMongoClient.__getattr__&s^ ??3  :&&''9$AQRVQW(4 %%rc.tj||S)rc)rGDatabasergs rrfzMongoClient.__getitem__5s  t,,rc $ |jrn|jsatjdt |j d|j jdt |j dtdyyy#ttf$rYywxYw)zGCheck that this MongoClient has been closed and issue a warning if not.z Unclosed z opened at: zCall z?.close() to safely shut down your client and free up resources.) stacklevelN) rrwarningsrrrPr_stackResourceWarningrerrs r__del__zMongoClient.__del__?s ||DLL #DJ$7$7#8 dF]F]FdFdEeT 3 344su$ %1| *   sA8A==BBc@|jj|||fy)z;Request that a cursor and/or connection be cleaned up soon.N)rappend)r cursor_idr6conn_mgrs r_close_cursor_soonzMongoClient._close_cursor_soonOs   '')X(FGrc pt}tjdi|}tj||||Sr)rLrFSessionOptionsrh)rimplicitrserver_sessionrs r_start_sessionzMongoClient._start_sessionXs4,.,,6v6++D.$QQrc,|jd|||S)aStart a logical session. This method takes the same parameters as :class:`~pymongo.client_session.SessionOptions`. See the :mod:`~pymongo.client_session` module for details and examples. A :class:`~pymongo.client_session.ClientSession` may only be used with the MongoClient that started it. :class:`ClientSession` instances are **not thread-safe or fork-safe**. They can only be used by one thread or process at a time. A single :class:`ClientSession` cannot be used to run multiple operations concurrently. :return: An instance of :class:`~pymongo.client_session.ClientSession`. .. versionadded:: 3.6 F)causal_consistencydefault_transaction_optionssnapshot)r{)rr}r~rs r start_sessionzMongoClient.start_session]s(,"" 1(C #  rc\|r|S |jddS#ttf$rYywxYw)6If provided session is None, lend a temporary session.TF)r}N)r{r#r%rs r_ensure_sessionzMongoClient._ensure_sessionzs? N &&t&F F"$45  s ++c|jj}|r |jnd}|r|r|d|dkDr|}n |}n|xs|}|r||d<yy)N clusterTime $clusterTime)rmax_cluster_time cluster_time)rcommandr topology_time session_timers r_send_cluster_timezMongoClient._send_cluster_timesb779 /6w++D \]+l=.II6C + (8LL &2GN # rc|j | tdtt|jxs|}t j ||||||S)a\Get the database named in the MongoDB connection URI. >>> uri = 'mongodb://host/my_database' >>> client = MongoClient(uri) >>> db = client.get_default_database() >>> assert db.name == 'my_database' >>> db = client.get_database() >>> assert db.name == 'my_database' Useful in scripts where you want to choose which database to use based only on the URI in a configuration file. :param default: the database name to use if no database name was provided in the URI. :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. :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. :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. :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. :param comment: A user-provided comment to attach to this command. .. versionchanged:: 4.1 Added ``comment`` parameter. .. versionchanged:: 3.8 Undeprecated. Added the ``default``, ``codec_options``, ``read_preference``, ``write_concern`` and ``read_concern`` parameters. .. versionchanged:: 3.5 Deprecated, use :meth:`get_database` instead. z-No default database name defined or provided.)rr#rrrGrj)rdefaultrrrrrs rget_default_databasez MongoClient.get_default_databasesXh  & & .7?$%TU UC44?@  $  |  rc|#|j td|j}tj||||||S)a?Get a :class:`~pymongo.database.Database` with the given name and options. Useful for creating a :class:`~pymongo.database.Database` with different codec options, read preference, and/or write concern from this :class:`MongoClient`. >>> client.read_preference Primary() >>> db1 = client.test >>> db1.read_preference Primary() >>> from pymongo import ReadPreference >>> db2 = client.get_database( ... 'test', read_preference=ReadPreference.SECONDARY) >>> db2.read_preference Secondary(tag_sets=None) :param name: The name of the database - a string. If ``None`` (the default) the database named in the MongoDB connection URI is returned. :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. :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. :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. :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. .. versionchanged:: 3.5 The `name` parameter is now optional, defaulting to the database named in the MongoDB connection URI. zNo default database defined)rr#rGrj)rrrrrrs r get_databasezMongoClient.get_databasesMd <**2()FGG..D  $  |  rcX|j|ttjtS)z2Get a Database instance with the default settings.)rrr)rrr@PRIMARYr`rgs r_database_default_optionsz%MongoClient._database_default_options s,  /*22/ !  rc|Srrrs r __enter__zMongoClient.__enter__ rc$|jyr)rrexc_typeexc_valexc_tbs r__exit__zMongoClient.__exit__s  rctd)Nz$'MongoClient' object is not iterable)rrs r__next__zMongoClient.__next__s>??rc|jjttj}t |j |S)aAn attribute of the current server's description. If the client is not connected, this will block until a connection is established or raise ServerSelectionTimeoutError if no server is available. Not threadsafe if used multiple times in a single method, since the server may change. In such cases, store a local reference to a ServerDescription first, then use its properties. )r select_serverrDr?TESTgetattrr0)r attr_nameservers r_server_propertyzMongoClient._server_property$s:$$&556NPSPXPXYv))955rc$|j|j|jjj}|tj k(r1t |jjdkDr td|jdS)a(host, port) of the current standalone, primary, or mongos, or None. Accessing :attr:`address` raises :exc:`~.errors.InvalidOperation` if the client is load-balancing among mongoses, since there is no single address. Use :attr:`nodes` instead. If the client is not connected, this will block until a connection is established or raise ServerSelectionTimeoutError if no server is available. .. versionadded:: 3.0 rzVCannot use "address" property when load balancing among mongoses, use "nodes" instead.r6) rr _description topology_typerQShardedrr2server_descriptionsr%r)rrs rr6zMongoClient.address3s~ >> !    33AA ]22 2D--AACDqH"2 $$Y//rcn|j|j|jjS)aLThe (host, port) of the current primary of the replica set. Returns ``None`` if this client is not connected to a replica set, there is no primary, or this client was created without the `replicaSet` option. .. versionadded:: 3.0 MongoClient gained this property in version 3.0. )rr get_primaryrs rprimaryzMongoClient.primaryNs- >> !    ~~))++rcn|j|j|jjS)a`The secondary members known to this client. A sequence of (host, port) pairs. Empty if this client is not connected to a replica set, there are no visible secondaries, or this client was created without the `replicaSet` option. .. versionadded:: 3.0 MongoClient gained this property in version 3.0. )rrget_secondariesrs r secondarieszMongoClient.secondaries]s- >> !    ~~--//rcn|j|j|jjS)zArbiters in the replica set. A sequence of (host, port) pairs. Empty if this client is not connected to a replica set, there are no arbiters, or this client was created without the `replicaSet` option. )rr get_arbitersrs rarbiterszMongoClient.arbitersls- >> !    ~~**,,rc$|jdS)aPIf this client is connected to a server that can accept writes. True if the current server is a standalone, mongos, or the primary of a replica set. If the client is not connected, this will block until a connection is established or raise ServerSelectionTimeoutError if no server is available. is_writable)rrs r is_primaryzMongoClient.is_primaryxs$$]33rcF|jdtjk(S)zIf this client is connected to mongos. If the client is not connected, this will block until a connection is established or raise ServerSelectionTimeoutError if no server is available. server_type)rrEMongosrs r is_mongoszMongoClient.is_mongoss $$]3{7I7IIIrc |jtjdtj5\}}|j s dddyt dt|tjD]/}d|||tjzi}|jd|||1 dddy#1swYyxYw#t$rYywxYw)z7Send endSessions command(s) with the given session ids.N operationr endSessionsr )rr) _conn_for_readsr@PRIMARY_PREFERREDr? END_SESSIONSsupports_sessionsrangerr_MAX_END_SESSIONSrr()r session_idsconn read_prefispecs r _end_sessionszMongoClient._end_sessionss %%00$#BRBR& X-- X Xq#k"2F4L4LMXA);q1v?W?W;W+XYDLL$ RVLWX X X X   s;0B8B,B8 AB,#B8,B51B85B88 CCc|jy|jj}|r|j||jj |j |jj |j r|j j d|_tsItj|jj|jjdyy)aCleanup client resources and disconnect from MongoDB. End all server sessions created by this client by sending one or more endSessions commands. Close all sockets in the connection pools and stop the monitor threads. .. versionchanged:: 4.0 Once closed, the client cannot be used again and any attempt will raise :exc:`~pymongo.errors.InvalidOperation`. .. versionchanged:: 3.6 End all server sessions created by this client. NT)return_exceptions) rpop_all_sessionsrr r_process_kill_cursorsrrrasynciogathercleanup_monitorsr\)rrs rrzMongoClient.closes >> ! nn557    { + ##))+ ""$  ?? OO ! ! #  NN//1++002"& rctsR|jtj|_n,|jtjk7r t d|j s|j dr |j|j|jj|j5|jjdddd|_|jS#1swYxYw)zGet the internal :class:`~pymongo.topology.Topology` object. If this client was created with "connect=False", calling _get_topology launches the connection process in the background. NzCannot use MongoClient in different event loop. MongoClient uses low-level asyncio APIs that bind it to the event loop it was created on.rT) rrrget_running_loop RuntimeErrorrrrrropenrr rs rrzMongoClient._get_topologys zz!$557 w7799"`||%%h/!!#%%' NN   ! 3++002 3DL~~ 3 3s :C00C9c#~K|xr |j}t|||5}|rA|r?|jr3|j|j|j dddy|j |5}|rJ|rH|j j tjtjfvr|j|||j||jr0|jjs|jdkr td|ddddddy#1swYxYw#1swYyxYww)N)handlerz9Auto-encryption requires a minimum MongoDB version of 4.2)r_MongoClientErrorHandler_pinned_connectioncontribute_socketcheckoutr0rrEr LoadBalancer_pinr_bypass_auto_encryptionmax_wire_versionr#)rrrin_txn err_handlerrs r _checkoutzMongoClient._checkouts*3W33 %dFG <  'g&@&@--g.H.HI000    5 **66#**#00 LL.--d3OO OOCC--1,S +          sAD=;D1 D=$D16BD%D1 D=%D. *D11D:6D=c |j}|r&|js|jj|s|r |j}|r&|j |||}|st d|z|S|j||||}|S#t$r5} |r-|jr!| jd|jd} ~ wwxYw)aSelect a server to run an operation on this client. :Parameters: - `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 be pinned to a mongos server address. - `address` (optional): Address when sending a message to a specific server, used for getMore. ) operation_idz server %s:%s no longer available)deprioritized_serversrTransientTransactionErrorN) rr _transactionr_pinned_addressselect_server_by_addressr rr(_add_error_label_unpin) rrrrr6rrtopologyrexcs r_select_serverzMongoClient._select_servers& ))+Hw55$$**,w!11!::Y\;'(JW(TUUM "//#*?!- 0 M 711$$%@A   sA/B 2B C0CCcT|jt||}|j||Sr)rrDr)rrrrs r_conn_for_writeszMongoClient._conn_for_writes1s*$$%=w R~~fg..rc#lK|Jd|jjjtjk(}|j ||5}|rG|j r|r |jstj}n|jrtj}||fdddy#1swYyxYwwNz read_preference must not be None) rr0rrQSingleris_replrr@r is_standaloner)rrrrsinglers r_conn_from_serverzMongoClient._conn_from_server7s*N,NN*++99]=Q=QQ ^^FG , (<<W5K5K'5&F&FO''&4&<&._cmd|s: OO ''%%  r)r6 retryabler) rOptional[ClientSession]rrnrrmrrArre)rurrrrrrrrrr_retryable_readrr6)rrrr6rrrs``` r_run_operationzMongoClient._run_operationZsk   (())!! )F##)) -dFIr? KILL_CURSORSrrDrr!)r cursor_idsr6rrrrs rr"zMongoClient._kill_cursorsss 66uW~sGWGWXF++,DcFVFVWF ^^FG , G& &&  " ":w F G G Gs #BBcz|j}|jdd\}}||d}|j||||y)NrMr) killCursorscursors)rr) namespacesplitr) rr%r6rrr)dbcollrs rr!zMongoClient._kill_cursor_implsA%% ??3*D# ; Rwt D E1EEc |j|jjy#t$r?}t |t r|jj rYd}~ytYd}~yd}~wwxYw)zcProcess any pending kill cursors requests and maintain connection pool parameters. N)rr update_poolr0rr%rr2)rrs rrz#MongoClient._process_periodic_taskssV $  & & ( NN & & ( $#/0T^^5K5K!##  $s*- A5&A0! A00A5cZt|try|jj|S)z.Internal: return a _ServerSession to the pool.N)rrLrreturn_server_session)rrzs r_return_server_sessionz"MongoClient._return_server_sessions' n&9 :~~33NCCrc#K|6t|tjstdt ||y|j |}|r | |r|jyydy#t $r@}t|tr|jj|jd}~wwxYw#|r|jwwxYww)rNz8'session' argument must be a ClientSession or None, not ) rrFrh ValueErrorrrr0r$_server_session mark_dirty end_session)rrrr7rs rrzMongoClient._tmp_sessions  g~'C'CD NtT[}o^M    )  $MMOJ c#45%%002   MMOs6A CA-C- B66;B11B66B99CCc|jj|jd||j|yy)Nr)rreceive_cluster_timer_process_response)rreplyrs rr?zMongoClient._process_responses6 ++EIIn,EF    % %e , rcvtt|jjdtj |S)zGet information about the MongoDB server we're connected to. :param session: a :class:`~pymongo.client_session.ClientSession`. .. versionchanged:: 3.6 Added ``session`` parameter. buildinfo)rr)rrr rr@rrs r server_infozMongoClient.server_infos8  JJ  ^-C-CW    rc ddi}|j||||d<|jd}|j||tj}d|ddd }t |d |d| S) N listDatabasesrr*r )rrr databasesz admin.$cmd)id firstBatchnsz$cmd)r*)rr_retryable_read_commandr?LIST_DATABASESrM)rrr*rcmdr rcursors r_list_databaseszMongoClient._list_databases s " 6  $C N..w7++CCL^L^+_k*  U6]FD'JJrc *|j||fi|S)aGet a cursor over the databases of the connected server. :param session: a :class:`~pymongo.client_session.ClientSession`. :param comment: A user-provided comment to attach to this command. :param kwargs: Optional parameters of the `listDatabases command `_ can be passed as keyword arguments to this method. The supported options differ by server version. :return: An instance of :class:`~pymongo.command_cursor.CommandCursor`. .. versionadded:: 3.6 rN)rrr*rs rlist_databaseszMongoClient.list_databases s.$t##GW???rcZ|j|d|}|Dcgc]}|d c}Scc}w)a`Get a list of the names of all databases on the connected server. :param session: a :class:`~pymongo.client_session.ClientSession`. :param comment: A user-provided comment to attach to this command. .. versionchanged:: 4.1 Added ``comment`` parameter. .. versionadded:: 3.6 T)nameOnlyr*rrP)rrr*rdocs rlist_database_nameszMongoClient.list_database_names3 s3"""7T7"K'*+F +++s (c |}t|tjr |j}t|tst dt ||j|tj5}||j|d|dtj|j|d|dddy#1swYyxYw)aDrop a database. Raises :class:`TypeError` if `name_or_database` is not an instance of :class:`str` or :class:`~pymongo.database.Database`. :param name_or_database: the name of a database to drop, or a :class:`~pymongo.database.Database` instance representing the database to drop :param session: a :class:`~pymongo.client_session.ClientSession`. :param comment: A user-provided comment to attach to this command. .. versionchanged:: 4.1 Added ``comment`` parameter. .. versionchanged:: 3.6 Added ``session`` parameter. .. note:: The :attr:`~pymongo.mongo_client.MongoClient.write_concern` of this client is automatically applied to this operation. .. versionchanged:: 3.4 Apply this client's write concern automatically to this operation when connected to MongoDB >= 3.4. z?name_or_database must be an instance of str or a Database, not rr) dropDatabaser*T)rrparse_write_concern_errorrN)rrGrjrrrrrr? DROP_DATABASE_commandr@r_write_concern_for)rname_or_databaserr*rrs r drop_databasezMongoClient.drop_databaseG sD  dH-- .99D$$QRVW[R\Q]^  " "7c6G6G " H D J  !"w7 . 6 6"55g>*.     s 1;B55B>c >|jjr td|r:|jr.|r td|jj j }n|s |j }|r|js |r td|r|js |r tdtjd|t|||||||} |D]} | j| | j|tj S#t$rt| ddwxYw) aSend a batch of write operations, potentially across multiple namespaces, to the server. Requests are passed as a list of write operation instances ( :class:`~pymongo.operations.InsertOne`, :class:`~pymongo.operations.UpdateOne`, :class:`~pymongo.operations.UpdateMany`, :class:`~pymongo.operations.ReplaceOne`, :class:`~pymongo.operations.DeleteOne`, or :class:`~pymongo.operations.DeleteMany`). >>> for doc in db.test.find({}): ... print(doc) ... {'x': 1, '_id': ObjectId('54f62e60fba5226811f634ef')} {'x': 1, '_id': ObjectId('54f62e60fba5226811f634f0')} ... >>> for doc in db.coll.find({}): ... print(doc) ... {'x': 2, '_id': ObjectId('507f1f77bcf86cd799439011')} ... >>> # DeleteMany, UpdateOne, and UpdateMany are also available. >>> from pymongo import InsertOne, DeleteOne, ReplaceOne >>> models = [InsertOne(namespace="db.test", document={'y': 1}), ... DeleteOne(namespace="db.test", filter={'x': 1}), ... InsertOne(namespace="db.coll", document={'y': 2}), ... ReplaceOne(namespace="db.test", filter={'w': 1}, replacement={'z': 1}, upsert=True)] >>> result = client.bulk_write(models=models) >>> result.inserted_count 2 >>> result.deleted_count 1 >>> result.modified_count 0 >>> result.upserted_count 1 >>> for doc in db.test.find({}): ... print(doc) ... {'x': 1, '_id': ObjectId('54f62e60fba5226811f634f0')} {'y': 1, '_id': ObjectId('54f62ee2fba5226811f634f1')} {'z': 1, '_id': ObjectId('54f62ee28891e756a6e1abd5')} ... >>> for doc in db.coll.find({}): ... print(doc) ... {'x': 2, '_id': ObjectId('507f1f77bcf86cd799439011')} {'y': 2, '_id': ObjectId('507f1f77bcf86cd799439012')} :param models: A list of write operation instances. :param session: (optional) An instance of :class:`~pymongo.client_session.ClientSession`. :param ordered: If ``True`` (the default), requests will be performed on the server serially, in the order provided. If an error occurs all remaining operations are aborted. If ``False``, requests will be still performed on the server serially, in the order provided, but all operations will be attempted even if any errors occur. :param verbose_results: If ``True``, detailed results for each successful operation will be included in the returned :class:`~pymongo.results.ClientBulkWriteResult`. Default is ``False``. :param bypass_document_validation: (optional) If ``True``, allows the write to opt-out of document level validation. Default is ``False``. :param comment: (optional) A user-provided comment to attach to this command. :param let: (optional) Map of parameter names and values. Values must be constant or closed expressions that do not reference document fields. Parameters can then be accessed as variables in an aggregate expression context (e.g. "$$var"). :param write_concern: (optional) The write concern to use for this bulk write. :return: An instance of :class:`~pymongo.results.ClientBulkWriteResult`. .. seealso:: For more info, see :doc:`/examples/client_bulk`. .. seealso:: :ref:`writes-and-ids` .. note:: requires MongoDB server version 8.0+. .. versionadded:: 4.9 zFMongoClient.bulk_write does not currently support automatic encryptionz5Cannot set write concern after starting a transactionz?Cannot request unacknowledged write concern and verbose resultsz>Cannot request unacknowledged write concern and ordered writesmodels)rorderedbypass_document_validationr*letverbose_resultsz is not a valid requestN)rrr%rrrr acknowledgedr validate_listrK_add_to_client_bulkrerexecuter? BULK_WRITE) rr_rr`rcrar*rbrblkmodels r bulk_writezMongoClient.bulk_write| s2x == - -"X  w--&'^__#0055CCM! $ 2 2 !;!;"Q =#=#='"#cd dXv. ''A+  OE O))#. O {{7CNN33" O5)+B CD$N Os DD)NNNNNN)rxz#Optional[Union[str, Sequence[str]]]ry Optional[int]rszOptional[Type[_DocumentType]]rtOptional[bool]rurmrzzOptional[TypeRegistry]rrrNonerrn)rzCollection[tuple[str, int]]rrrrrrn)r!common._CaseInsensitiveDictionaryrzset[tuple[str, int | None]]rrp)r~rprrprrpr)r rlrrn)rrrrn)rrrrm)rrrrq) NNNNNNNNNNNN)r"zOptional[_Pipeline]r# Optional[str]r$Optional[Mapping[str, Any]]r%rlr&rlr'zOptional[_CollationIn]r(zOptional[Timestamp]r&Optional[client_session.ClientSession]r)rrr* Optional[Any]r+rqrrmrzChangeStream[_DocumentType])rrR)rzFrozenSet[_Address])rr)rz>tuple[tuple[_Address, ...], Optional[str], Optional[str], str])rDrrr)rr)rr)rrr database.Database[_DocumentType])rtrr6Optional[_CursorAddress]ruOptional[_ConnectionManager]rrn)ryrrrrrh)NNF)r}rmr~z+Optional[client_session.TransactionOptions]rrmrzclient_session.ClientSession)rrrr)rzMutableMapping[str, Any]rrrrn)NNNNN) rrqr(Optional[CodecOptions[_DocumentTypeArg]]rOptional[_ServerMode]rOptional[WriteConcern]rOptional[ReadConcern]rru) rrqrrxrryrrzrr{rru)rrrzdatabase.Database)rzMongoClient[_DocumentType])rrrrrrrrn)rr)rrrr)rzOptional[tuple[str, int]])rz set[_Address]r)rzlist[_ServerSession]rrn)rrO)rrnrrrzGenerator[Connection, None])NNN)rz Callable[[Selection], Selection]rrrrr6Optional[_Address]rzOptional[list[Server]]rrlrrn)rrrrrzContextManager[Connection])rrArrnrrrz/Generator[tuple[Connection, _ServerMode], None])rrArrrrrz.ContextManager[tuple[Connection, _ServerMode]])rzUnion[_Query, _GetMore]rrr6r|rre)rrr _WriteCall[T]rrr#Optional[Union[_Bulk, _ClientBulk]]rrrrlrro)FNNFN)r_WriteCall[T] | _ReadCall[T]rrrr~rrr rr6r|rryrrrrlrro)NTN)rz _ReadCall[T]rrArrrrr6r|rrrrlrro)NN)rrrr}rrrrrr~rrlrro) rtrr6rvrurjrrrrrrn) rtrr6rvrrrurwrrn) r% Sequence[int]r6rvrrOrrrrn) r%rr6r4rrrrmrrn)rzz*Union[_ServerSession, _EmptyServerSession]rrnT)rrsrrrz=Generator[Optional[client_session.ClientSession], None, None])r@zMapping[str, Any]rrrrn)rrsrzdict[str, Any])rrsr*rtrrrzCommandCursor[dict[str, Any]])rrsr*rtrz list[str])r\z/Union[str, database.Database[_DocumentTypeArg]]rrsr*rtrrn)NTFNNNN)r_z!Sequence[_WriteOp[_DocumentType]]rrr`rrcrrarmr*rtrbzOptional[Mapping]rrzrrB)ZrPrO __qualname__rrrZrWeakValueDictionaryrv__annotations__rrrrrrrrrrrr-propertyr2r:rr@rErGrJr]rarhrfrqrvr{rrrrrrrr__iter__rnextrr6rrrrrrrrr contextlibcontextmanagerrrrrrrapplyrr r rrrrrr"r!rrr7rr?rCrNrQrUr]rk __classcell__)rs@rrqrqs' D DB,GG,G,G,IH)I59"8<#'"&04C !1C !C !6 C ! ! C !  C !.C !C ! C !JCPJ.0.AD.X[. .:5>Y * 7 0  + < AX- #)-'+48+/$(,07;:>37!%59/3A%A%A2 A ) A " A*A"5A8A1AA&3A-A %AF**< G G  !%""H? &-(26 HH*H/ H  HR.2SW#(  * &Q !  &  :  3/ 3:Q 3  3""&BF1504.2 : : @: / : . : , :  *: |#BF1504.2 9 9 @9 / 9 . 9 , 9  *9 v H@ D 6004 , , 0 0 - -44JJ,"H .'> $L'+8<&*-9-)- - $ - 6 -$- -^/./;>/ #/ (*(4:(E\( 8((0H$H)H H 8 H [[ '+ 8 *8 8 $ 8  8 8 B'+   )  2    $   < [[&*+/&*$*$)$2 $  $  $$$)$$$$ $$X'+&*) ) ) ) )  ) $ ) ) $)  ) b59&*___) _  _ 2 _$_ _2,,*,% , ) ,  , ,0 , ,* ,% , ) ,  ,  ,L,015 88*8) 8 / 8  86G!G*G G ) G  G( =! =  =) =  =  =&,R $DHD DMQ=FJ F>-  $;?!%K7KK K ' K,;?!%@7@@ @ ' @6;?!%,7,,  ,( [[;?!% 2I282 2  22h [[,0 %59!%!%04B41B4)B4 B4  B4 %3 B4B4B4.B4 B4B4rrqct|ttfr|jd}|r|dSdSt|tt fr't tttf|jSy)z:Return the server response from PyMongo exception or None.writeConcernErrorsN) rr!r"detailsr&r'rr rr)rwcess r_retryable_error_docr sa#(@AB{{/0tBx)T)#)9:;GCH%s{{33 rc*t|}|r|jdd}|dk(r3t|jdrd}t |||j |dk\r)|jdgD]}|j |n6t|tr|rn#|tjvr|j dt|tr |j}n|}t|tr)t|ttfs|j dyyy) NcoderzTransaction numberszrThis MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string. errorLabelsRetryableWriteError)rrrrr'rrrr+r_RETRYABLE_ERROR_CODESr"errorr$r&r*)rrrrTrerrmsglabel exc_to_checks r_add_retryable_write_errorr s s #C wwvq! 2:#c(--.CD-  #64= = q 3 ,$$U+ ,#01i>>>$$%:;#/0yy  , 12:(=>< %%&;<<2rcZeZdZdZdZd dZd d dZ d dZd dZ ddZ y)rz1Handle errors raised when executing an operation.)rserver_addressrrsock_generationcompleted_handshake service_idhandledct|tsFtdt|jDs!t dt|j ||_|jj|_ ||_ tj|_|jj j#|_d|_d|_d|_y)Nc3:K|]}|jdk(yw)rqN)rP)rclss rrz4_MongoClientErrorHandler.__init__..B sUs||}4UszMongoClient required but given F)rrqanyr__mro__rrPrr0r6rrrMIN_WIRE_VERSIONrpoolgen get_overallrrrr)rrrrs rrz!_MongoClientErrorHandler.__init__? s&+.UV @T@TUU"A$v,BWBWAX YZZ $0088 & 7 7 &{{::<#( .2 rcx|j|_|j|_|j|_||_y)z0Provide socket information to the error handler.N)r generationrrr)rrrs rrz*_MongoClientErrorHandler.contribute_socketR s/ $ 5 5#//#6 rc|js|yd|_|jrt|tr |j}t|t rK|jj r|jd|jjjt|tr<|jds|jdr|jjt||j|j|j |j"}|j$j&J|j$j&j)|j*|y)NTrr)rrrr"rr$rrr:r;r(has_error_labelrrPrrrrrr handle_errorr)rrrerr_ctxs rhandlez_MongoClientErrorHandler.handleY s <<7?  <<'#;<!--'#45<<..,,-HI ,,779'<0**+FG7KbKb)LLL'')   ! !   $ $ OO  {{$$000 **4+>+>Hrc|Srrrs rrz"_MongoClientErrorHandler.__enter__v rrc&|j||Sr)rrs rrz!_MongoClientErrorHandler.__exit__y s {{8W--rN)rrqrrnrrr)rrmrrrrn)rzOptional[Type[BaseException]]rzOptional[BaseException]rrn)rr)rzOptional[Type[Exception]]rzOptional[Exception]rzOptional[TracebackType]rrn) rPrOr__doc__ __slots__rrrrrrrrrr1 sg; I&7I5I@WI I:.+.%.( .  .rrceZdZdZ d d dZddZddZddZddZdddZ dd Z dd Z dd Z y)rzKResponsible for executing retryable connections on read or write operationsNc *d|_d|_tjdu|_||_||_||_||_||_ | |_ ||_ |r|nt|_ ||_d|_g|_||_| |_d|_y)NFr) _last_error _retryingr get_timeout_multiple_retries_client_func_bulkr_is_read _retryable _read_prefrD_server_selector_address_server_deprioritized_servers _operation _operation_id_attempt_number) rr rrrr rrr6rrs rrz#_ClientConnectionRetryable.__init__ s15!&!2!2!4D!@#     ## I&>   # 46##) rc|jrO|jrC|js7|jj |j rd|j _ |jd |jr|jS|jS#t$r|jt$r2}|jr{t|ttfrdt|dd}|j!s"t|tr|t"j$vrd|_||_|xj*dz c_n|js>|jst|t,rD|j.r8t|j.txr|j.j1d}n|j1d}|r(|jsJ|jj3|r|j!r+|j1dr|j(r |j(||xj*dz c_|j rd|j _nd|_|j1ds||_|j(||_|j6j8j:t<j>k(r%|j@jC|jDYd}~nd}~wwxYw)zRuns the supplied func() and attempts a retry :raises: self._last_error: Last exception raised :return: Result of the func() call T) check_csotrNrrNoWritesPerformed)#_is_session_state_retryablerrr_start_retryable_writerstarted_retryable_write_check_last_error_read_writer)r(rr$r'r_is_not_eligible_for_retryrrrrrr"rrrretryingrr2rrQrrrsr)rrexc_coderetryable_write_error_excs rrz_ClientConnectionRetryable.run sc  + + -$//$-- MM 0 0 2zz59 2  " "d " 39 E'+}}tzz|G$++-G. &&(. E==!#(9;K'LM#*3#=::<&s,<= (0U0U U!)-+.(,,1,}}??!#'?@SYY4>II|55O!ii778MN2584G4GH]4^10#}},} ,,.48W8W8Y../BCHXHX"&"2"2;!((A-(zz.2 +)-../BC+.(''/+.(<<44BBmF[F[[//66t||D]. Es4B B #K5H(K00K5c^|j xs|jxr |j S)z0Checks if the exchange is not eligible for retry)r _is_retryingrrs rrz5_ClientConnectionRetryable._is_not_eligible_for_retry s+??"Zt'8'8':'Y4CYCY?YZrc^|jr|jjS|jS)z6Checks if the exchange is currently undergoing a retry)rrrrs rrz'_ClientConnectionRetryable._is_retrying s!&*jjtzz""DdnnDrc|jr%|jxr|jj St|jxr|jj S)zChecks if provided session is eligible for retry reads: Make sure there is no ongoing transaction (if provided a session) writes: Make sure there is a session without an active transaction )rrrrrs rrz6_ClientConnectionRetryable._is_session_state_retryable sH == F$--*F*FG GDMMF$--*F*F&FGGrc|jr9tj}|r| |dkr|jJ|jyyy)zChecks if the ongoing client exchange experienced a exception previously. If so, raise last error :param check_csot: Checks CSOT to ensure we are retrying with time remaining defaults to False Nr)rr remainingr)rrrs rrz,_ClientConnectionRetryable._check_last_error sV    )I)"7IN''333&&&=K"7 rc|jj|j|j|j|j |j |jS)zvRetrieves a server object based on provided object context :return: Abstraction to connect to server )r6rr)rrrrrrrrrs r _get_serverz&_ClientConnectionRetryable._get_server sP ||**  ! ! MM OOMM"&"="=++ +  rc d}d}|j|_|jj|j|j5}|j }|jxr.|jj jxr |j}|j}|s|jd|_ |jrSttd|j|jj j"|j$|j&|j)|j||jcdddS#1swYyxYw#t*$r }|jst-|d}~wwxYw)zmWrapper method for write-type retryable client executions :return: Output for func()'s call rFzRetrying write attempt number messageclientId commandName operationIdN)rrrrrrr0retryable_writes_supportedrrrrrr1r0rrrrrrr(r)rrrrsessions_supportedrs rrz!_ClientConnectionRetryable._write sE   I++-DL'' dmmD H#'#8#8 MM/ 00KK/..# !NN )**,&+DO>>'"@AUAU@V W!%!@!@!M!M$(OO$($6$6 zz$--tG+ H H H, ?? &s, EE EE E=E88E=cX|j|_|jJd|jj |j|j|j 5\}}|j r|js|j|j rSttd|j|jjj|j|j|j!|j |j||cdddS#1swYyxYw)zlWrapper method for read-type retryable client executions :return: Output for func()'s call Nz&Read Preference required on read callszRetrying read attempt number r)rrrrrrrrrr1r0rrrrrr)rrrs rrz _ClientConnectionRetryable._readE s '') *T,TT* \\ + +DOOT\\4== Y L^  ~~doo&&(~~#;Dr?pymongo.read_preferencesr@rApymongo.resultsrBpymongo.server_descriptionrCpymongo.server_selectorsrDpymongo.server_typerEpymongo.synchronousrFrGrH!pymongo.synchronous.change_streamrIrJpymongo.synchronous.client_bulkrK"pymongo.synchronous.client_sessionrL"pymongo.synchronous.command_cursorrMpymongo.synchronous.settingsrNpymongo.synchronous.topologyrOrPpymongo.topology_descriptionrQrRpymongo.typingsrSrTrUrVrWrXpymongo.uri_parser_sharedrYrZr[r\r]r^r_pymongo.write_concernr`ratypesrb bson.objectidrcpymongo.read_concernrdpymongo.responsererfpymongo.synchronous.bulkrgrhripymongo.synchronous.cursorrjrrlpymongo.synchronous.poolrmpymongo.synchronous.serverrnror _WriteCall _ReadCallr_WriteOp BaseObjectrqrrrrrrregister_at_forkrrrrs$# #(QP$DD0*     =<FA18=+DDO7B<9@KF#&0)2.P=931 CL x0,EqH I  o, D        U%4&##W]%;U%4pJ  =FN.N.bXLXLv 2B'89 r