o Sbq@sFdZddlZddlZddlZddlmZddlmZmZm Z m Z m Z m Z m Z mZmZmZmZmZmZmZmZddlmZmZmZddlmZddlmZddlmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&dd l'm(Z(m)Z)dd l*m+Z+dd l,m-Z-dd l.m/Z/dd l0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:ddl;mZ>m?Z?ddl@mAZAddlBmCZCddlDmEZEddlFmGZGmHZHddlImJZJmKZKddlLmMZMmNZNmOZOmPZPddlQmRZRmSZSmTZTmUZUddlVmWZWmXZXerddlYZYddlZm[Z[eYj\dddkrddl]m^Z^nddlm^Z^Gddde!j_e eOZ`ddZad d!ZbGd"d#d#ecZddS)$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') N) defaultdict) TYPE_CHECKINGAnyDict FrozenSetGenericListMappingNoReturnOptionalSequenceSetTupleTypeUnioncast)DEFAULT_CODEC_OPTIONS CodecOptions TypeRegistry)SON) Timestamp)_csotclient_sessioncommondatabasehelpersmessageperiodic_executor uri_parser) ChangeStreamClusterChangeStream) ClientOptions)_EmptyServerSession) CommandCursor) AutoReconnectBulkWriteErrorConfigurationErrorConnectionFailureInvalidOperationNotPrimaryErrorOperationFailure PyMongoErrorServerSelectionTimeoutErrorWaitQueueTimeoutError)ConnectionClosedReason)ReadPreference _ServerMode)writable_server_selector) SERVER_TYPE)TopologySettings)Topology _ErrorContext) TOPOLOGY_TYPETopologyDescription)_Address _CollationIn _DocumentType _Pipeline)_check_options_handle_option_deprecations_handle_security_options_normalize_options)DEFAULT_WRITE_CONCERN WriteConcern) ReadConcern) ) GeneratorcsZeZdZdZdZdZdZ      ddeee e e fdee dee e d eed eed eed ed dffdd ZddZddZ           ddeedee deee efdee dee deedeedeejdeee efdeedee d ee fdd Zed efd!d"Zed eee e ffd#d$Z ed eee e ffd%d&Z!ed e"ee e ffd'd(Z#ed e"ee e ffd)d*Z$ed efd+d,Z%ed efd-d.Z&ed e'e(fd/d0Z)ed e*fd1d2Z+d3d4Z,dd5d6Z-d7d8Z.e/j0d9d:Z1dd;d<Z2d=d>Z3e/j0d?d@Z4dAdBZ5dCdDZ6e7j8ddEdFZ9dGdHZ:e7j8dIdJZ;e7j8ddLdMZdPed efdSdTZ?d e fdUdVZ@dWdXZAdYdZZBd[e d eCjDe fd\d]ZEd[e d eCjDe fd^d_ZFd`daZGddbdcZHddddeZIdfdgZJdhdiZKdjdkZLdldmZMdndoZN   pddqeedreejOdseed ejfdtduZPdvdwZQdxdyZRddzd{ZSe/j0 Kddeejd|ed d}fd~dZTddZUddZVddeejd eWe effddZX  ddeejdeed ed eYeWe effddZZ  ddeejdeed e[e fddZ\e7j8  ddee eCjDfdeejdeed dfddZ]     ddee dee^dee_dee`dedd eCjDe f ddZa     dd[ee dee^dee_dee`dedd eCjDe f ddZbddZcdddZddededed dfddZedZfd egfddZhehZiZjS) MongoClienta| A client-side representation of a MongoDB cluster. Instances can represent either a standalone MongoDB server, a replica set, or a sharded cluster. Instances of this class are responsible for maintaining up-to-date state of the cluster, and possibly cache resources related to this, including background threads for monitoring, and connection pools. localhostii)document_classtz_awareconnectNhostportrIrJrK type_registrykwargsreturnc s||pt}||||||d||_|dur|j}t|tr|g}|dur&|j}t|ts/td|dd} |dd} |dd} t ||d<t } d} d}d}t }d} d} d }t d d |Dd krrtd |D]P}d|vr d}|durt d|}tj||ddd|||d}| |d|dp| } |dp|}|dp|}|d}|d}qt| t||qt| std|dur|d<|dur| dd}|dur| dd}|d<|d<tt tfddD||dur| dt j}|p| d }t|}t|}t| || d| } | d|}t| ||||_}||_t|_ g|_!|j"j#|_#t$t%|&|j'|j(|j)|j*t+| |j,| |j"| | |j-|j.|j/|j0||j1|j2||d |_3t4|j3|_5fd!d"}t6j7t j8t j9|d#d$}t:;||j<||_=|r|>d|_?|jj@rd%d&lAmB}|||jj@|_?|jC|_DdS)'atClient 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. :Parameters: - `host` (optional): 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 documents returned from queries on this client - `tz_aware` (optional): 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 begin connecting to MongoDB in the background. Otherwise connect on the first operation. - `type_registry` (optional): instance of :class:`~bson.codec_options.TypeRegistry` to enable encoding and decoding of custom types. | **Other optional parameters can be passed as keyword arguments:** - `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. - `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.rst - `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. - `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") | **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`: (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 SCRAM-SHA-1 when connected to MongoDB 3.6 and negotiates the mechanism to use (SCRAM-SHA-1 or SCRAM-SHA-256) when connected to MongoDB 4.0+. - `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. Only supported by python 2.7.9+ (pypy 2.5.1+). 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. Only supported by python 2.7.9+ (pypy 2.5.1+) and 3.3+. 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.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`` and ``maxConnecting`` URI and keyword argument. .. 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__ )rLrMrIrJrKrNNzport must be an instance of intZ _pool_classZ_monitor_classZ_condition_classrIZsrvservicenameZ srvmaxhostscSsg|]}d|vr|qS)/).0hrRrR;/tmp/pip-target-onvjaxws/lib/python/pymongo/mongo_client.py sz(MongoClient.__init__..z+host must not contain multiple MongoDB URIsrQZconnecttimeoutmsTF)validatewarn normalizeconnect_timeoutsrv_service_name srv_max_hostsZnodelistusernamepasswordroptionsfqdnz!need to specify at least one hostrNrJrKc3s&|]\}}t||VqdSN)rrX cased_key)rSkv) keyword_optsrRrU s$z'MongoClient.__init__..ZsrvServiceName)seedsreplica_set_name pool_class pool_options monitor_classcondition_classlocal_threshold_msserver_selection_timeoutserver_selectorheartbeat_frequencyradirect_connection load_balancedr\r]cs }|dur dSt|dS)NFT)rG_process_periodic_tasks)client)self_refrRrUtarget.s  z$MongoClient.__init__..targetZpymongo_kill_cursors_thread)intervalZ min_intervalrwnamer) _Encrypter)Edict_MongoClient__init_kwargsHOST isinstancestrPORTint TypeErrorpoprZ_CaseInsensitiveDictionarysetgetlenr&Z validate_timeout_or_none_or_zerorcr parse_uriupdateZ split_hostsr=itemsZSRV_SERVICE_NAMEr>r?r<r!_MongoClient__options#_MongoClient__default_database_name threadingLock_MongoClient__lock _MongoClient__kill_cursors_queuerk_event_listenerssuperrG__init__ codec_optionsread_preference write_concern read_concernr3rirnrorprqrrrs_topology_settingsr4 _topologyrZPeriodicExecutorZKILL_CURSOR_FREQUENCYZMIN_HEARTBEAT_INTERVALweakrefrefclose_kill_cursors_executor _get_topology _encrypterZauto_encryption_optsZpymongo.encryptionrztimeout_timeout)selfrLrMrIrJrKrNrOZ doc_classrjrlrmrhr^r_Zdbaseoptsrar\r]entityrresr`rwexecutorrz __class__)rfrvrUrs%                               zMongoClient.__init__cKs"|j}||tdi|SNrR)r|copyrrG)rrOargsrRrRrU _duplicateKs  zMongoClient._duplicatecCs|jt}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_serverr1getattr description)r attr_nameserverrRrRrU_server_propertyPs zMongoClient._server_propertypipeline full_document resume_aftermax_await_time_ms batch_size collationstart_at_operation_timesession start_aftercommentfull_document_before_changec Cs t|j||||||||| | | S)aWatch changes on this cluster. Performs an aggregation with an implicit initial ``$changeStream`` stage and returns a :class:`~pymongo.change_stream.ClusterChangeStream` cursor which iterates over changes on all databases on this cluster. Introduced in MongoDB 4.0. .. code-block:: python with client.watch() as stream: for change in stream: print(change) The :class:`~pymongo.change_stream.ClusterChangeStream` iterable blocks until the next change document is returned or an error is raised. If the :meth:`~pymongo.change_stream.ClusterChangeStream.next` method encounters a network error when retrieving a batch from the server, it will automatically attempt to recreate the cursor such that no change events are missed. Any error encountered during the resume attempt indicates there may be an outage and will be raised. .. code-block:: python try: with client.watch( [{'$match': {'operationType': 'insert'}}]) as stream: for insert_change in stream: print(insert_change) except pymongo.errors.PyMongoError: # The ChangeStream encountered an unrecoverable error or the # resume attempt failed to recreate the cursor. logging.error('...') For a precise description of the resume process see the `change streams specification`_. :Parameters: - `pipeline` (optional): 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 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' and 'required'. Change events may now result in a 'fullDocumentBeforeChange' response field. - `resume_after` (optional): 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 for the server to wait for changes before responding to a getMore operation. - `batch_size` (optional): The maximum number of documents to return per batch. - `collation` (optional): The :class:`~pymongo.collation.Collation` to use for the aggregation. - `start_at_operation_time` (optional): 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 :class:`~pymongo.client_session.ClientSession`. - `start_after` (optional): 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 command. :Returns: A :class:`~pymongo.change_stream.ClusterChangeStream` cursor. .. 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.rst )r admin) rrrrrrrrrrrrrRrRrUwatch_snzMongoClient.watchcCs|jjS)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`. :Returns: An instance of :class:`~pymongo.topology_description.TopologyDescription`. .. versionadded:: 4.0 )rrrrRrRrUtopology_descriptionsz MongoClient.topology_descriptioncCsT|jjj}|tjkrt|jdkrtd|tj tj tj tjfvr%dS| dS)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 rWzVCannot use "address" property when load balancing among mongoses, use "nodes" instead.Naddress) rZ _description topology_typer6ZShardedrrZserver_descriptionsr(ZReplicaSetWithPrimarySingleZ LoadBalancedr)rrrRrRrUrs  zMongoClient.addresscC |jS)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. )rZ get_primaryrrRrRrUprimary zMongoClient.primarycCr)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. )rZget_secondariesrrRrRrU secondariesrzMongoClient.secondariescCr)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. )rZ get_arbitersrrRrRrUarbiters,s zMongoClient.arbiterscCs |dS)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)rrrRrRrU is_primary6s zMongoClient.is_primarycCs|dtjkS)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)rr2MongosrrRrRrU is_mongosAszMongoClient.is_mongoscCs|jj}tdd|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. css|]}|jVqdSrbr)rSsrRrRrUrgUsz$MongoClient.nodes..)rr frozensetZ known_servers)rrrRrRrUnodesIs zMongoClient.nodescCs|jS)zThe configuration options for this client. :Returns: An instance of :class:`~pymongo.client_options.ClientOptions`. .. versionadded:: 4.0 )rrrRrRrUr`Ws zMongoClient.optionscCszN|tjd<\}}|js WdWdStdt|tjD]}td|||tjfg}|j d|||dq!WdWdS1sGwYWdSt yXYdSw)z7Send endSessions command(s) with the given session ids.NrZ endSessionsr)rru) _socket_for_readsr/PRIMARY_PREFERREDZsupports_sessionsrangerrZ_MAX_END_SESSIONSrcommandr+)r session_ids sock_info read_prefispecrRrRrU _end_sessionsbs& zMongoClient._end_sessionscCsL|j}|r |||j||j|jr$|jdSdS)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. N)rZpop_all_sessionsrrr_process_kill_cursorsr)rrrRrRrUrvs    zMongoClient.closecCsD|j|j|jWd|jS1swY|jS)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. N)ropenrrrrRrRrUrs   zMongoClient._get_topologyc cs|o|j}t|||i}|r%|jr%||j|jV WddS|j|d2}|r>|jjtjtj fvr>| |||||j rS|j j sS|j dkrStd|VWdn1s`wYWddSWddS1sxwYdS)N)handlerz9Auto-encryption requires a minimum MongoDB version of 4.2)in_transaction_MongoClientErrorHandlerZ_pinned_connectioncontribute_socketZ get_socketrrr2rZ LoadBalancerZ_pinrZ_bypass_auto_encryptionmax_wire_versionr&)rrrZin_txn err_handlerrrRrRrU _get_sockets:      "zMongoClient._get_socketc Csz/|}|r|js|j|p|o|j}|r(||}|s%td||WS||}|WStyJ}z|rE|jrE| d| d}~ww)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. z server %s:%d no longer availableTransientTransactionErrorN) rrZ _transactionresetZ_pinned_addressselect_server_by_addressr$rr+_add_error_label_unpin)rrprrtopologyrexcrRrRrU_select_servers&        zMongoClient._select_servercCs|t|}|||Srb)rr1r)rrrrRrRrU_socket_for_writess  zMongoClient._socket_for_writesccs|dus Jd|}|jjtjk}|||"}|r/|jr)|r%|js)tj }n|j r/tj }||fVWddS1s?wYdSNz read_preference must not be None) rrrr6rrZis_replrr/rZ is_standalonePRIMARY)rrrrrsinglerrRrRrU_socket_from_servers "zMongoClient._socket_from_servercCs2|dusJd|}|||}||||Sr)rrr)rrr_rrRrRrUrs zMongoClient._socket_for_readscCs|jjo |o|j Srb)rrsrrrrRrRrU_should_pin_cursorszMongoClient._should_pin_cursorc sjrRjjj|d}jj9t|j"}|jj|jjdj WdWdS1s>wYWdn1sMwYfdd}j |jj|t t j dS)aWRun 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 to a specific server, used for getMore. rTNcs|||jSrb)r run_operationr)rrrr operationr unpack_resrRrU_cmds z(MongoClient._run_operation.._cmd)r retryable)sock_mgrrrrlockrrsockrr_retryable_readr~rZ_Query)rrrrrrrrRrrU_run_operations,    zMongoClient._run_operationcCs(|o |jjo |o |j }|||||S)Execute an operation with at most one consecutive retries Returns func()'s return value on success. On error retries the same command once. Re-raises any exception thrown by func(). )r`Z retry_writesr_retry_internal)rrfuncrbulkrRrRrU_retry_with_sessions zMongoClient._retry_with_sessionc sd}d}dtdu}fdd}|r#|r#|js#|r#d_ |r;t} | dur;| dkr;|dus9J|zA|t|} |duoI| jj } | | |#} | j }|re| se|rc|dusaJ|d}||| |WdWS1svwYWnIt y|r|dusJ|t y} z+|st| || d}|r||r|r|srd_nd| }WYd} ~ nd} ~ wwq$) Internal retryable write helper.rNFcsrjSSrb)retryingrRrrrRrU is_retrying3z0MongoClient._retry_internal..is_retryingTRetryableWriteError)r get_timeoutrZ_start_retryable_writeZstarted_retryable_write remainingrr1rZretryable_writes_supportedrrr,r+_add_retryable_write_errorhas_error_labelrr)rrrrrr last_errormultiple_retriesr r rZsupports_sessionrrZretryable_errorrRrrUr+sb     &    zMongoClient._retry_internalTc Csn|o |jjo |o |j }d}d}tdu} |r-t} | dur-| dkr-|dus+J|z7|j|||d} ||| |\} }|rL|sL|dusJJ|||| | |WdWS1s^wYWnQtyv|ru|dussJ|t y} z|r|r|sd}| }WYd} ~ n(d} ~ wt y} z|r|r|s| j t j vrd}| }WYd} ~ nd} ~ wwq)rNFTrr)r`Z retry_readsrrr r rrr,r'r*coder_RETRYABLE_ERROR_CODES) rrrrrrrrrr rrrrRrRrUrnsP     &     zMongoClient._retryable_readcCs>||}||||dWdS1swYdS)rN) _tmp_sessionr)rrrrrrRrRrU_retryable_writes $zMongoClient._retryable_writeothercCst||jr |j|jkStSrb)r~rrNotImplementedrrrRrRrU__eq__s  zMongoClient.__eq__cCs ||k SrbrRrrRrRrU__ne__ zMongoClient.__ne__cCs t|jSrb)hashrrrRrRrU__hash__rzMongoClient.__hash__csddddddjjDg}|fddjD|fddjjDd |S) NcSsV|dkr|tur dSd|j|jfS|tjvr%|dur%d|t|dfSd||fS)z9Fix options whose __repr__ isn't usable in a constructor.rIzdocument_class=dictzdocument_class=%s.%sNz%s=%siz%s=%r)r{ __module____name__rZTIMEOUT_OPTIONSr)optionvaluerRrRrU option_reprs z-MongoClient._repr_helper..option_reprzhost=%rcSs(g|]\}}|durd||fn|qS)Nz%s:%drR)rSrLrMrRrRrUrVsz,MongoClient._repr_helper..c3s"|] }|jj|VqdSrb)r_optionsrSkeyr"rrRrUrgs z+MongoClient._repr_helper..c3s@|]}|tjvr|dkr|dkr|jj|VqdS)r^r_N)r_constructor_argsrr#r$r&rRrUrgs  z, )rrhextendr'rr#join)rr`rRr&rU _repr_helpers zMongoClient._repr_helpercCsd|fS)NzMongoClient(%s))r*rrRrRrU__repr__r zMongoClient.__repr__rycCs&|drtd|||f||S)Get a database by name. Raises :class:`~pymongo.errors.InvalidName` if an invalid database name is used. :Parameters: - `name`: the name of the database to get rzKMongoClient has no attribute %r. To access the %s database, use client[%r].) startswithAttributeError __getitem__rryrRrRrU __getattr__s  zMongoClient.__getattr__cCs t||S)r,)rDatabaser0rRrRrUr/s zMongoClient.__getitem__cCsx|r!|r|r|jr|jtjn |j||||d|r |n |s%|r,|||||r8|s:|j|ddSdSdS)aCleanup a cursor from cursor.close() or __del__. This method handles cleanup for Cursors/CommandCursors including any 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. - `sock_mgr`: The _SocketManager for the pinned connection or None. - `session`: The cursor's session. - `explicit_session`: True if the session was passed explicitly. )rr)rN) Z more_to_comerZ close_socketr.ERROR_close_cursor_nowr_close_cursor_soonZ _end_session)rZ locks_allowed cursor_idrrrZexplicit_sessionrRrRrU_cleanup_cursors zMongoClient._cleanup_cursorcCs|j|||fdS)z;Request that a cursor and/or connection be cleaned up soon.N)rappend)rr6rrrRrRrUr5szMongoClient._close_cursor_sooncCst|ts tdz2|r.|j||g|||jWdWdS1s&wYWdS||g|||WdStyK| ||YdSw)zzSend a kill cursors message with the given id. The cursor is closed synchronously on the current thread. z$cursor_id must be an instance of intN) r~rrr_kill_cursor_implr _kill_cursorsrr+r5)rr6rrrrRrRrUr4s & zMongoClient._close_cursor_nowcCs`|r |t|}n|t}|||}|||||WddS1s)wYdS)z/Send a kill cursors message with the given ids.N)rtuplerr1rr9)r cursor_idsrrrrrrRrRrUr:.s  "zMongoClient._kill_cursorsc Cs@|j}|dd\}}td|fd|fg}|j||||ddS)N.rWZ killCursorsZcursors)rru) namespacesplitrr) rr<rrrr>dbZcollrrRrRrUr9;szMongoClient._kill_cursor_implc Cs@tt}g} z |j\}}}Wn tyYnw|r&||||fn|||q|D]1\}}}z |d|||ddWq0tya}zt|t rS|j j rSt WYd}~q0d}~ww|r|}|D]1\}}z |j|||ddWqlty}zt|t r|j j rt WYd}~qld}~wwdSdS)z*Process any pending kill cursors requests.TNFr)rlistrr IndexErrorr8r7 Exceptionr~r(r_closedr_handle_exceptionrrr:) rZaddress_to_cursor_idsZpinned_cursorsrr6rrrr<rRrRrUrAsD   z!MongoClient._process_kill_cursorsc Cshz ||jWdSty3}zt|tr$|jjr$WYd}~dStWYd}~dSd}~ww)zZProcess any pending kill cursors requests and maintain connection pool parameters.N) rrZ update_poolrDr~r(rErrF)rrrRrRrUrtjsz#MongoClient._process_periodic_taskscKs>|r |jt}n|}tjdi|}t||||Sr)rZ_check_implicit_session_supportr"_get_server_sessionrZSessionOptions ClientSession)rZimplicitrOserver_sessionrrRrRrUZ__start_sessionvs  zMongoClient.__start_sessionFcausal_consistencydefault_transaction_optionssnapshotcCs|jd|||dS)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. :Returns: An instance of :class:`~pymongo.client_session.ClientSession`. .. versionadded:: 3.6 F)rJrKrL)_MongoClient__start_session)rrJrKrLrRrRrU start_sessions zMongoClient.start_sessioncCr)z+Internal: start or resume a _ServerSession.)rZget_server_sessionrrRrRrUrGs zMongoClient._get_server_sessioncCst|trdS|j||S)z.Internal: return a _ServerSession to the pool.N)r~r"rZreturn_server_session)rrIrrRrRrU_return_server_sessions z"MongoClient._return_server_sessionc Cs2|r|Sz|jdddWSttfyYdSw)6If provided session is None, lend a temporary session.TF)rJN)rMr&r(rrRrRrU_ensure_sessionszMongoClient._ensure_sessionrz=Generator[Optional[client_session.ClientSession], None, None]c cs|durt|tjstd|VdS||}|rPz,z|VWnty<}zt|tr3|j| d}~wwW|rF| dSdS|rO| wwdVdS)rPNz3'session' argument must be a ClientSession or None.) r~rrH ValueErrorrQrDr'_server_session mark_dirtyZ end_session)rrrrrrRrRrUrs0        zMongoClient._tmp_sessioncCsX|j}|r |jnd}|r|r|d|dkr|}n|}n|p!|}|r*||d<dSdS)NZ clusterTime $clusterTime)rZmax_cluster_time cluster_time)rrrZ topology_timeZ session_timerVrRrRrU_send_cluster_times  zMongoClient._send_cluster_timecCs,|j|d|dur||dSdS)NrU)rZreceive_cluster_timer_process_response)rZreplyrrRrRrUrXszMongoClient._process_responsecCstt|jjdtj|dS)aGet information about the MongoDB server we're connected to. :Parameters: - `session` (optional): a :class:`~pymongo.client_session.ClientSession`. .. versionchanged:: 3.6 Added ``session`` parameter. Z buildinfo)rr)rr{rrr/rrrRrRrU server_infos  zMongoClient.server_infocKs`tdg}|||dur||d<|d}|j||d}d|ddd }t|d |d|d S) aGet a cursor over the databases of the connected server. :Parameters: - `session` (optional): a :class:`~pymongo.client_session.ClientSession`. - `comment` (optional): A user-provided comment to attach to this command. - `**kwargs` (optional): Optional parameters of the `listDatabases command `_ 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`. .. versionadded:: 3.6 )Z listDatabasesrWNrrrArZ databasesz admin.$cmd)idZ firstBatchnsz$cmd)r)rr_database_default_optionsZ_retryable_read_commandr#)rrrrOcmdrrcursorrRrRrUlist_databasess   zMongoClient.list_databasescCsdd|j|d|dDS)aGet a list of the names of all databases on the connected server. :Parameters: - `session` (optional): a :class:`~pymongo.client_session.ClientSession`. - `comment` (optional): A user-provided comment to attach to this command. .. versionchanged:: 4.1 Added ``comment`` parameter. .. versionadded:: 3.6 cSsg|]}|dqS)ryrR)rSdocrRrRrUrV/sz3MongoClient.list_database_names..T)ZnameOnlyr)r_)rrrrRrRrUlist_database_namesszMongoClient.list_database_namesname_or_databasec Cs|}t|tjr |j}t|tstd||}||j|d|dtj | |d|dWddS1s9wYdS)aDrop a database. Raises :class:`TypeError` if `name_or_database` is not an instance of :class:`basestring` (:class:`str` in python 3) or :class:`~pymongo.database.Database`. :Parameters: - `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 :class:`~pymongo.client_session.ClientSession`. - `comment` (optional): 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. z9name_or_database must be an instance of str or a DatabaserW)Z dropDatabaserT)rrZparse_write_concern_errorrN) r~rr2ryrrrZ_commandr/rZ_write_concern_for)rrbrrryrrRrRrU drop_database1s$   "zMongoClient.drop_databasedefaultrrrrrBcCs>|jdur |dur tdtt|jp|}t||||||S)aGet 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. :Parameters: - `default` (optional): the database name to use if no database name was provided in the URI. - `codec_options` (optional): 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 ``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 :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 :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 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. Nz-No default database name defined or provided.)rr&rrrr2)rrdrrrrryrRrRrUget_default_databasefs 5 z MongoClient.get_default_databasecCs4|dur|jdur td|j}t||||||S)aGet 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) :Parameters: - `name` (optional): 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 :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 ``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 :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 :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. NzNo default database defined)rr&rr2)rryrrrrrRrRrU get_databases3  zMongoClient.get_databasecCs|j|ttjtdS)z2Get a Database instance with the default settings.)rrr)rfrr/rr@r0rRrRrUr\s z%MongoClient._database_default_optionsMongoClient[_DocumentType]cC|SrbrRrrRrRrU __enter__zMongoClient.__enter__exc_typeexc_valexc_tbcCs |dSrb)rrrkrlrmrRrRrU__exit__ zMongoClient.__exit__cCstd)Nz$'MongoClient' object is not iterable)rrrRrRrU__next__szMongoClient.__next__)NNNNNN) NNNNNNNNNNN)rPNrb)NT)NNN)NNFT)NN)NNNNN)rPrg)krr __qualname____doc__r}rr'r rrr rrr:boolrrrrrr;r r9rrrHrrpropertyr7rrrrr rrrrrr8rr!r`rrr contextlibcontextmanagerrrrrrrrapplyrrrrrrrrr*r+rr2r1r/r7r5r4r:r9rrtrMZTransactionOptionsrNrGrOrQrrWrXrrYr#r_rrarcrr0rArerfr\riro__iter__r rqnext __classcell__rRrRrrUrGqs   N     }          # B 6! #  )       " )   6 ? <  rGcCsDt|tr|jd}|r|d}|Sd}|St|ttfr |jSdS)z:Return the server response from PyMongo exception or None.ZwriteConcernErrorsN)r~r%detailsr)r*)rZwcesZwcerRrRrU_retryable_error_docs   rcCst|}|r=|dd}|dkr t|dr d}t|||j|dkr3|dgD]}||q*n |tjvr=|dt |t rPt |t t fsR|ddSdSdS) NrrzTransaction numberszrThis MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.rEZ errorLabelsr ) rrrr-r*r~rrrr~r'r)r-)rrr`rerrmsglabelrRrRrUrs$     rc@s>eZdZdZdZddZdddZdd Zd d Zd d Z dS)rz1Handle errors raised when executing an operation.)ruserver_addressrrsock_generationcompleted_handshake service_idhandledcCsB||_|jj|_||_tj|_|jj |_ d|_ d|_ d|_dS)NF)rurrrrrZMIN_WIRE_VERSIONrpoolgenZ get_overallrrrr)rrurrrRrRrUr.s  z!_MongoClientErrorHandler.__init__TcCs"|j|_|j|_|j|_||_dS)z0Provide socket information to the error handler.N)rZ generationrrr)rrrrRrRrUr<s z*_MongoClientErrorHandler.contribute_socketcCs|js|dur dSd|_|jr7t|tr#|jjr|d|jjt|tr7| ds2| dr7|j t ||j |j |j|j}|jj|j|dS)NTrr )rr issubclassr'rrrSrTr+rrr5rrrrrur handle_errorr)rrkrlZerr_ctxrRrRrUhandleCs*     z_MongoClientErrorHandler.handlecCrhrbrRrrRrRrUri\rjz"_MongoClientErrorHandler.__enter__cCs |||Srb)rrnrRrRrUro_rpz!_MongoClientErrorHandler.__exit__Nrr) rrrsrt __slots__rrrrirorRrRrRrUr s  r)ertrwrr collectionsrtypingrrrrrrr r r r r rrrrZbson.codec_optionsrrrZbson.sonrZbson.timestamprZpymongorrrrrrrrZpymongo.change_streamrr Zpymongo.client_optionsr!Zpymongo.client_sessionr"Zpymongo.command_cursorr#Zpymongo.errorsr$r%r&r'r(r)r*r+r,r-Z pymongo.poolr.Zpymongo.read_preferencesr/r0Zpymongo.server_selectorsr1Zpymongo.server_typer2Zpymongo.settingsr3Zpymongo.topologyr4r5Zpymongo.topology_descriptionr6r7Zpymongo.typingsr8r9r:r;Zpymongo.uri_parserr<r=r>r?Zpymongo.write_concernr@rAsysZpymongo.read_concernrB version_infocollections.abcrFZ BaseObjectrGrrobjectrrRrRrRrUsd D  (   0