desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Represent MongoClient\'s configuration. Take a list of (host, port) pairs and optional replica set name.'
def __init__(self, seeds=None, replica_set_name=None, pool_class=None, pool_options=None, monitor_class=None, condition_class=None, local_threshold_ms=LOCAL_THRESHOLD_MS, server_selection_timeout=SERVER_SELECTION_TIMEOUT, heartbeat_frequency=common.HEARTBEAT_FREQUENCY):
if (heartbeat_frequency < common.MIN_HEARTBEAT_INTERVAL): raise ConfigurationError((('heartbeatFrequencyMS cannot be less than %d' % common.MIN_HEARTBEAT_INTERVAL) * 1000)) self._seeds = (seeds or [('localhost', 27017)]) self._replica_set_name = replica_set_name self._pool_class = (pool_class or pool.Pool) self._pool_options = (pool_options or PoolOptions()) self._monitor_class = (monitor_class or monitor.Monitor) self._condition_class = (condition_class or threading.Condition) self._local_threshold_ms = local_threshold_ms self._server_selection_timeout = server_selection_timeout self._heartbeat_frequency = heartbeat_frequency self._direct = ((len(self._seeds) == 1) and (not replica_set_name)) self._topology_id = ObjectId()
'List of server addresses.'
@property def seeds(self):
return self._seeds
'Connect directly to a single server, or use a set of servers? True if there is one seed and no replica_set_name.'
@property def direct(self):
return self._direct
'Initial dict of (address, ServerDescription) for all seeds.'
def get_server_descriptions(self):
return dict([(address, ServerDescription(address)) for address in self.seeds])
'The error code returned by the server, if any.'
@property def code(self):
return self.__code
'The complete error document returned by the server. Depending on the error that occurred, the error document may include useful information beyond just the error message. When connected to a mongos the error document may contain one or more subdocuments if errors occurred on multiple shards.'
@property def details(self):
return self.__details
'Client for a MongoDB instance, a replica set, or a set of mongoses. 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 <http://dochub.mongodb.org/core/connections>`_, in addition to a simple hostname. It can also be a list of hostnames or URIs. Any port specified in the host string(s) will override the `port` parameter. If multiple mongodb URIs containing database or auth information are passed, the last database, username, and password present will be used. For username and passwords reserved characters like \':\', \'/\', \'+\' and \'@\' must be percent encoded following RFC 2396:: try: # Python 3.x from urllib.parse import quote_plus except ImportError: # Python 2.x from urllib 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\') .. 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 ismaster command is cheap and does not require auth. client.admin.command(\'ismaster\') except ConnectionFailure: print("Server not available") .. warning:: When using PyMongo in a multiprocessing context, please read :ref:`multiprocessing` first. :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 / mongodb URIs. 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. | **Other optional parameters can be passed as keyword arguments:** - `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. Cannot be 0. - `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). - `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. 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. Defaults to ``20000`` (20 seconds). - `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). - `waitQueueMultiple`: (integer or None) Multiplied by maxPoolSize to give the number of threads allowed to wait for a socket at one time. Defaults to ``None`` (no limit). - `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. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections. - `event_listeners`: a list or tuple of event listeners. See :mod:`~pymongo.monitoring` for details. - `socketKeepAlive`: (boolean) **DEPRECATED** Whether to send periodic keep-alive packets on connected sockets. Defaults to ``True``. Disabling it is not recommended, see https://docs.mongodb.com/manual/faq/diagnostics/#does-tcp-keepalive-time-affect-mongodb-deployments", | **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=<int>` 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. - `wtimeout`: (integer) Used in conjunction with `w`. Specify a value in milliseconds to control how long to wait for write propagation to complete. If replication does not complete in the given timeframe, a timeout exception is raised. - `j`: If ``True`` block until write operations have been committed to the journal. Cannot be used in combination with `fsync`. Prior to MongoDB 2.6 this option was ignored if the server was running without journaling. Starting with MongoDB 2.6 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. | **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. By default, use SCRAM-SHA-1 with MongoDB 3.0 and later, MONGODB-CR (MongoDB Challenge Response protocol) for older servers. - `authMechanismProperties`: Used to specify authentication mechanism specific options. To specify the service name for GSSAPI authentication pass authMechanismProperties=\'SERVICE_NAME:<service name>\' .. seealso:: :doc:`/examples/authentication` | **SSL configuration:** - `ssl`: If ``True``, create the connection to the server using SSL. Defaults to ``False``. - `ssl_certfile`: The certificate file used to identify the local connection against mongod. Implies ``ssl=True``. Defaults to ``None``. - `ssl_keyfile`: The private keyfile used to identify the local connection against mongod. If included with the ``certfile`` then only the ``ssl_certfile`` is needed. Implies ``ssl=True``. Defaults to ``None``. - `ssl_pem_passphrase`: The password or passphrase for decrypting the private key in ``ssl_certfile`` or ``ssl_keyfile``. 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``. - `ssl_cert_reqs`: Specifies whether a certificate is required from the other side of the connection, and whether it will be validated if provided. It must be one of the three values ``ssl.CERT_NONE`` (certificates ignored), ``ssl.CERT_REQUIRED`` (certificates required and validated), or ``ssl.CERT_OPTIONAL`` (the same as CERT_REQUIRED, unless the server was configured to use anonymous ciphers). If the value of this parameter is not ``ssl.CERT_NONE`` and a value is not provided for ``ssl_ca_certs`` PyMongo will attempt to load system provided CA certificates. If the python version in use does not support loading system CA certificates then the ``ssl_ca_certs`` parameter must point to a file of CA certificates. Implies ``ssl=True``. Defaults to ``ssl.CERT_REQUIRED`` if not provided and ``ssl=True``. - `ssl_ca_certs`: The ca_certs file contains a set of concatenated "certification authority" certificates, which are used to validate certificates passed from the other end of the connection. Implies ``ssl=True``. Defaults to ``None``. - `ssl_crlfile`: The path to a PEM or DER formatted certificate revocation list. Only supported by python 2.7.9+ (pypy 2.5.1+) and 3.4+. Defaults to ``None``. - `ssl_match_hostname`: If ``True`` (the default), and `ssl_cert_reqs` is not ``ssl.CERT_NONE``, enables hostname verification using the :func:`~ssl.match_hostname` function from python\'s :mod:`~ssl` module. Think very carefully before setting this to ``False`` as that could make your application vulnerable to man-in-the-middle attacks. | **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. .. mongodoc:: connections .. 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 </examples/copydb>` 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__'
def __init__(self, host=None, port=None, document_class=dict, tz_aware=None, connect=None, **kwargs):
if (host is None): host = self.HOST if isinstance(host, string_type): host = [host] if (port is None): port = self.PORT if (not isinstance(port, int)): raise TypeError('port must be an instance of int') seeds = set() username = None password = None dbase = None opts = {} for entity in host: if ('://' in entity): if entity.startswith('mongodb://'): res = uri_parser.parse_uri(entity, port, warn=True) seeds.update(res['nodelist']) username = (res['username'] or username) password = (res['password'] or password) dbase = (res['database'] or dbase) opts = res['options'] else: idx = entity.find('://') raise InvalidURI(('Invalid URI scheme: %s' % (entity[:idx],))) else: seeds.update(uri_parser.split_hosts(entity, port)) if (not seeds): raise ConfigurationError('need to specify at least one host') pool_class = kwargs.pop('_pool_class', None) monitor_class = kwargs.pop('_monitor_class', None) condition_class = kwargs.pop('_condition_class', None) keyword_opts = kwargs keyword_opts['document_class'] = document_class if (tz_aware is None): tz_aware = opts.get('tz_aware', False) if (connect is None): connect = opts.get('connect', True) keyword_opts['tz_aware'] = tz_aware keyword_opts['connect'] = connect keyword_opts = dict((common.validate(k, v) for (k, v) in keyword_opts.items())) opts.update(keyword_opts) username = opts.get('username', username) password = opts.get('password', password) if ('socketkeepalive' in opts): warnings.warn('The socketKeepAlive option is deprecated. It nowdefaults to true and disabling it is not recommended, see https://docs.mongodb.com/manual/faq/diagnostics/#does-tcp-keepalive-time-affect-mongodb-deployments', DeprecationWarning, stacklevel=2) self.__options = options = ClientOptions(username, password, dbase, opts) self.__default_database_name = dbase self.__lock = threading.Lock() self.__cursor_manager = None self.__kill_cursors_queue = [] self._event_listeners = options.pool_options.event_listeners self.__index_cache = {} self.__index_cache_lock = threading.Lock() super(MongoClient, self).__init__(options.codec_options, options.read_preference, options.write_concern, options.read_concern) self.__all_credentials = {} creds = options.credentials if creds: self._cache_credentials(creds.source, creds) self._topology_settings = TopologySettings(seeds=seeds, replica_set_name=options.replica_set_name, pool_class=pool_class, pool_options=options.pool_options, monitor_class=monitor_class, condition_class=condition_class, local_threshold_ms=options.local_threshold_ms, server_selection_timeout=options.server_selection_timeout, heartbeat_frequency=options.heartbeat_frequency) self._topology = Topology(self._topology_settings) if connect: self._topology.open() def target(): client = self_ref() if (client is None): return False MongoClient._process_periodic_tasks(client) return True executor = periodic_executor.PeriodicExecutor(interval=common.KILL_CURSOR_FREQUENCY, min_interval=0.5, target=target, name='pymongo_kill_cursors_thread') self_ref = weakref.ref(self, executor.close) self._kill_cursors_executor = executor executor.open()
'Save a set of authentication credentials. The credentials are used to login a socket whenever one is created. If `connect` is True, verify the credentials on the server first.'
def _cache_credentials(self, source, credentials, connect=False):
all_credentials = self.__all_credentials.copy() if (source in all_credentials): if (credentials == all_credentials[source]): return raise OperationFailure('Another user is already authenticated to this database. You must logout first.') if connect: server = self._get_topology().select_server(writable_preferred_server_selector) with server.get_socket(all_credentials) as sock_info: sock_info.authenticate(credentials) self.__all_credentials[source] = credentials
'Purge credentials from the authentication cache.'
def _purge_credentials(self, source):
self.__all_credentials.pop(source, None)
'Test if `index` is cached.'
def _cached(self, dbname, coll, index):
cache = self.__index_cache now = datetime.datetime.utcnow() with self.__index_cache_lock: return ((dbname in cache) and (coll in cache[dbname]) and (index in cache[dbname][coll]) and (now < cache[dbname][coll][index]))
'Add an index to the index cache for ensure_index operations.'
def _cache_index(self, dbname, collection, index, cache_for):
now = datetime.datetime.utcnow() expire = (datetime.timedelta(seconds=cache_for) + now) with self.__index_cache_lock: if (database not in self.__index_cache): self.__index_cache[dbname] = {} self.__index_cache[dbname][collection] = {} self.__index_cache[dbname][collection][index] = expire elif (collection not in self.__index_cache[dbname]): self.__index_cache[dbname][collection] = {} self.__index_cache[dbname][collection][index] = expire else: self.__index_cache[dbname][collection][index] = expire
'Purge an index from the index cache. If `index_name` is None purge an entire collection. If `collection_name` is None purge an entire database.'
def _purge_index(self, database_name, collection_name=None, index_name=None):
with self.__index_cache_lock: if (not (database_name in self.__index_cache)): return if (collection_name is None): del self.__index_cache[database_name] return if (not (collection_name in self.__index_cache[database_name])): return if (index_name is None): del self.__index_cache[database_name][collection_name] return if (index_name in self.__index_cache[database_name][collection_name]): del self.__index_cache[database_name][collection_name][index_name]
'An 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.'
def _server_property(self, attr_name):
server = self._topology.select_server(writable_server_selector) return getattr(server.description, attr_name)
'The event listeners registered for this client. See :mod:`~pymongo.monitoring` for details.'
@property def event_listeners(self):
return self._event_listeners.event_listeners
'(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'
@property def address(self):
topology_type = self._topology._description.topology_type if (topology_type == TOPOLOGY_TYPE.Sharded): raise InvalidOperation('Cannot use "address" property when load balancing among mongoses, use "nodes" instead.') if (topology_type not in (TOPOLOGY_TYPE.ReplicaSetWithPrimary, TOPOLOGY_TYPE.Single)): return None return self._server_property('address')
'The (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 when MongoReplicaSetClient\'s functionality was merged in.'
@property def primary(self):
return self._topology.get_primary()
'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 when MongoReplicaSetClient\'s functionality was merged in.'
@property def secondaries(self):
return self._topology.get_secondaries()
'Arbiters 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.'
@property def arbiters(self):
return self._topology.get_arbiters()
'If 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.'
@property def is_primary(self):
return self._server_property('is_writable')
'If 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..'
@property def is_mongos(self):
return (self._server_property('server_type') == SERVER_TYPE.Mongos)
'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. Cannot be 0. When a server\'s pool has reached `max_pool_size`, operations for that server block waiting for a socket to be returned to the pool. If ``waitQueueTimeoutMS`` is set, a blocked operation will raise :exc:`~pymongo.errors.ConnectionFailure` after a timeout. By default ``waitQueueTimeoutMS`` is not set.'
@property def max_pool_size(self):
return self.__options.pool_options.max_pool_size
'The minimum required number of concurrent connections that the pool will maintain to each connected server. Default is 0.'
@property def min_pool_size(self):
return self.__options.pool_options.min_pool_size
'The maximum number of milliseconds that a connection can remain idle in the pool before being removed and replaced. Defaults to `None` (no limit).'
@property def max_idle_time_ms(self):
return self.__options.pool_options.max_idle_time_ms
'Set 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.'
@property def nodes(self):
description = self._topology.description return frozenset((s.address for s in description.known_servers))
'The largest BSON object the connected server accepts in bytes. If the client is not connected, this will block until a connection is established or raise ServerSelectionTimeoutError if no server is available.'
@property def max_bson_size(self):
return self._server_property('max_bson_size')
'The largest message the connected server accepts in bytes. If the client is not connected, this will block until a connection is established or raise ServerSelectionTimeoutError if no server is available.'
@property def max_message_size(self):
return self._server_property('max_message_size')
'The maxWriteBatchSize reported by the server. If the client is not connected, this will block until a connection is established or raise ServerSelectionTimeoutError if no server is available. Returns a default value when connected to server versions prior to MongoDB 2.6.'
@property def max_write_batch_size(self):
return self._server_property('max_write_batch_size')
'The local threshold for this instance.'
@property def local_threshold_ms(self):
return self.__options.local_threshold_ms
'The server selection timeout for this instance in seconds.'
@property def server_selection_timeout(self):
return self.__options.server_selection_timeout
'Attempt to connect to a writable server, or return False.'
def _is_writable(self):
topology = self._get_topology() try: svr = topology.select_server(writable_server_selector) return svr.description.is_writable except ConnectionFailure: return False
'Disconnect from MongoDB. Close all sockets in the connection pools and stop the monitor threads. If this instance is used again it will be automatically re-opened and the threads restarted.'
def close(self):
self._process_periodic_tasks() self._topology.close()
'DEPRECATED - Set this client\'s cursor manager. Raises :class:`TypeError` if `manager_class` is not a subclass of :class:`~pymongo.cursor_manager.CursorManager`. A cursor manager handles closing cursors. Different managers can implement different policies in terms of when to actually kill a cursor that has been closed. :Parameters: - `manager_class`: cursor manager to use .. versionchanged:: 3.3 Deprecated, for real this time. .. versionchanged:: 3.0 Undeprecated.'
def set_cursor_manager(self, manager_class):
warnings.warn('set_cursor_manager is Deprecated', DeprecationWarning, stacklevel=2) manager = manager_class(self) if (not isinstance(manager, CursorManager)): raise TypeError('manager_class must be a subclass of CursorManager') self.__cursor_manager = manager
'Get 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.'
def _get_topology(self):
self._topology.open() return self._topology
'Send a message to MongoDB and return a Response. :Parameters: - `operation`: a _Query or _GetMore object. - `read_preference` (optional): A ReadPreference. - `exhaust` (optional): If True, the socket used stays checked out. It is returned along with its Pool in the Response. - `address` (optional): Optional address when sending a message to a specific server, used for getMore.'
def _send_message_with_response(self, operation, read_preference=None, exhaust=False, address=None):
with self.__lock: self._kill_cursors_executor.open() topology = self._get_topology() if address: server = topology.select_server_by_address(address) if (not server): raise AutoReconnect(('server %s:%d no longer available' % address)) else: selector = (read_preference or writable_server_selector) server = topology.select_server(selector) set_slave_ok = ((topology.description.topology_type == TOPOLOGY_TYPE.Single) and (server.description.server_type != SERVER_TYPE.Mongos)) return self._reset_on_error(server, server.send_message_with_response, operation, set_slave_ok, self.__all_credentials, self._event_listeners, exhaust)
'Execute an operation. Reset the server on network error. Returns fn()\'s return value on success. On error, clears the server\'s pool and marks the server Unknown. Re-raises any exception thrown by fn().'
def _reset_on_error(self, server, func, *args, **kwargs):
try: return func(*args, **kwargs) except NetworkTimeout: raise except ConnectionFailure: self.__reset_server(server.description.address) raise
'Clear our connection pool for a server and mark it Unknown.'
def __reset_server(self, address):
self._topology.reset_server(address)
'Clear our pool for a server, mark it Unknown, and check it soon.'
def _reset_server_and_request_check(self, address):
self._topology.reset_server_and_request_check(address)
'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'
def __getattr__(self, name):
if name.startswith('_'): raise AttributeError(('MongoClient has no attribute %r. To access the %s database, use client[%r].' % (name, name, name))) return self.__getitem__(name)
'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'
def __getitem__(self, name):
return database.Database(self, name)
'Send a kill cursors message soon with the given id. Raises :class:`TypeError` if `cursor_id` is not an instance of ``(int, long)``. What closing the cursor actually means depends on this client\'s cursor manager. This method may be called from a :class:`~pymongo.cursor.Cursor` destructor during garbage collection, so it isn\'t safe to take a lock or do network I/O. Instead, we schedule the cursor to be closed soon on a background thread. :Parameters: - `cursor_id`: id of cursor to close - `address` (optional): (host, port) pair of the cursor\'s server. If it is not provided, the client attempts to close the cursor on the primary or standalone, or a mongos server. .. versionchanged:: 3.0 Added ``address`` parameter.'
def close_cursor(self, cursor_id, address=None):
if (not isinstance(cursor_id, integer_types)): raise TypeError('cursor_id must be an instance of (int, long)') if (self.__cursor_manager is not None): self.__cursor_manager.close(cursor_id, address) else: self.__kill_cursors_queue.append((address, [cursor_id]))
'Send a kill cursors message with the given id. What closing the cursor actually means depends on this client\'s cursor manager. If there is none, the cursor is closed synchronously on the current thread.'
def _close_cursor_now(self, cursor_id, address=None):
if (not isinstance(cursor_id, integer_types)): raise TypeError('cursor_id must be an instance of (int, long)') if (self.__cursor_manager is not None): self.__cursor_manager.close(cursor_id, address) else: self._kill_cursors([cursor_id], address, self._get_topology())
'DEPRECATED - Send a kill cursors message soon with the given ids. Raises :class:`TypeError` if `cursor_ids` is not an instance of ``list``. :Parameters: - `cursor_ids`: list of cursor ids to kill - `address` (optional): (host, port) pair of the cursor\'s server. If it is not provided, the client attempts to close the cursor on the primary or standalone, or a mongos server. .. versionchanged:: 3.3 Deprecated. .. versionchanged:: 3.0 Now accepts an `address` argument. Schedules the cursors to be closed on a background thread instead of sending the message immediately.'
def kill_cursors(self, cursor_ids, address=None):
warnings.warn('kill_cursors is deprecated.', DeprecationWarning, stacklevel=2) if (not isinstance(cursor_ids, list)): raise TypeError('cursor_ids must be a list') self.__kill_cursors_queue.append((address, cursor_ids))
'Send a kill cursors message with the given ids.'
def _kill_cursors(self, cursor_ids, address, topology):
listeners = self._event_listeners publish = listeners.enabled_for_commands if address: server = topology.select_server_by_address(tuple(address)) else: server = topology.select_server(writable_server_selector) try: namespace = address.namespace (db, coll) = namespace.split('.', 1) except AttributeError: namespace = None db = coll = 'OP_KILL_CURSORS' spec = SON([('killCursors', coll), ('cursors', cursor_ids)]) with server.get_socket(self.__all_credentials) as sock_info: if ((sock_info.max_wire_version >= 4) and (namespace is not None)): sock_info.command(db, spec) else: if publish: start = datetime.datetime.now() (request_id, msg) = message.kill_cursors(cursor_ids) if publish: duration = (datetime.datetime.now() - start) listeners.publish_command_start(spec, db, request_id, tuple(address)) start = datetime.datetime.now() try: sock_info.send_message(msg, 0) except Exception as exc: if publish: dur = ((datetime.datetime.now() - start) + duration) listeners.publish_command_failure(dur, message._convert_exception(exc), 'killCursors', request_id, tuple(address)) raise if publish: duration = ((datetime.datetime.now() - start) + duration) reply = {'cursorsUnknown': cursor_ids, 'ok': 1} listeners.publish_command_success(duration, reply, 'killCursors', request_id, tuple(address))
'Process any pending kill cursors requests and maintain connection pool parameters.'
def _process_periodic_tasks(self):
address_to_cursor_ids = defaultdict(list) while True: try: (address, cursor_ids) = self.__kill_cursors_queue.pop() except IndexError: break address_to_cursor_ids[address].extend(cursor_ids) if address_to_cursor_ids: topology = self._get_topology() for (address, cursor_ids) in address_to_cursor_ids.items(): try: self._kill_cursors(cursor_ids, address, topology) except Exception: helpers._handle_exception() try: self._topology.update_pool() except Exception: helpers._handle_exception()
'Get information about the MongoDB server we\'re connected to.'
def server_info(self):
return self.admin.command('buildinfo', read_preference=ReadPreference.PRIMARY)
'Get a list of the names of all databases on the connected server.'
def database_names(self):
return [db['name'] for db in self._database_default_options('admin').command(SON([('listDatabases', 1), ('nameOnly', True)]))['databases']]
'Drop 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 .. note:: The :attr:`~pymongo.mongo_client.MongoClient.write_concern` of this client is automatically applied to this operation when using MongoDB >= 3.4. .. versionchanged:: 3.4 Apply this client\'s write concern automatically to this operation when connected to MongoDB >= 3.4.'
def drop_database(self, name_or_database):
name = name_or_database if isinstance(name, database.Database): name = name.name if (not isinstance(name, string_type)): raise TypeError(('name_or_database must be an instance of %s or a Database' % (string_type.__name__,))) self._purge_index(name) with self._socket_for_reads(ReadPreference.PRIMARY) as (sock_info, slave_ok): self[name]._command(sock_info, 'dropDatabase', slave_ok=slave_ok, read_preference=ReadPreference.PRIMARY, write_concern=self.write_concern, parse_write_concern_error=True)
'DEPRECATED - 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. .. versionchanged:: 3.5 Deprecated, use :meth:`get_database` instead.'
def get_default_database(self):
warnings.warn('get_default_database is deprecated. Use get_database instead.', DeprecationWarning, stacklevel=2) if (self.__default_database_name is None): raise ConfigurationError('No default database defined') return self[self.__default_database_name]
'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) :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.'
def get_database(self, name=None, codec_options=None, read_preference=None, write_concern=None, read_concern=None):
if (name is None): if (self.__default_database_name is None): raise ConfigurationError('No default database defined') name = self.__default_database_name return database.Database(self, name, codec_options, read_preference, write_concern, read_concern)
'Get a Database instance with the default settings.'
def _database_default_options(self, name):
return self.get_database(name, codec_options=DEFAULT_CODEC_OPTIONS, read_preference=ReadPreference.PRIMARY, write_concern=WriteConcern())
'Is this server locked? While locked, all write operations are blocked, although read operations may still be allowed. Use :meth:`unlock` to unlock.'
@property def is_locked(self):
ops = self._database_default_options('admin').current_op() return bool(ops.get('fsyncLock', 0))
'Flush all pending writes to datafiles. :Parameters: Optional parameters can be passed as keyword arguments: - `lock`: If True lock the server to disallow writes. - `async`: If True don\'t block while synchronizing. .. warning:: `async` and `lock` can not be used together. .. warning:: MongoDB does not support the `async` option on Windows and will raise an exception on that platform.'
def fsync(self, **kwargs):
self.admin.command('fsync', read_preference=ReadPreference.PRIMARY, **kwargs)
'Unlock a previously locked server.'
def unlock(self):
cmd = {'fsyncUnlock': 1} with self._socket_for_writes() as sock_info: if (sock_info.max_wire_version >= 4): try: sock_info.command('admin', cmd) except OperationFailure as exc: if (exc.code != 125): raise else: helpers._first_batch(sock_info, 'admin', '$cmd.sys.unlock', {}, (-1), True, self.codec_options, ReadPreference.PRIMARY, cmd, self._event_listeners)
'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. Cannot be 0. When a server\'s pool has reached `max_pool_size`, operations for that server block waiting for a socket to be returned to the pool. If ``waitQueueTimeoutMS`` is set, a blocked operation will raise :exc:`~pymongo.errors.ConnectionFailure` after a timeout. By default ``waitQueueTimeoutMS`` is not set.'
@property def max_pool_size(self):
return self.__max_pool_size
'The minimum required number of concurrent connections that the pool will maintain to each connected server. Default is 0.'
@property def min_pool_size(self):
return self.__min_pool_size
'The maximum number of milliseconds that a connection can remain idle in the pool before being removed and replaced. Defaults to `None` (no limit).'
@property def max_idle_time_ms(self):
return self.__max_idle_time_ms
'How long a connection can take to be opened before timing out.'
@property def connect_timeout(self):
return self.__connect_timeout
'How long a send or receive on a socket can take before timing out.'
@property def socket_timeout(self):
return self.__socket_timeout
'How long a thread will wait for a socket from the pool if the pool has no free sockets.'
@property def wait_queue_timeout(self):
return self.__wait_queue_timeout
'Multiplied by max_pool_size to give the number of threads allowed to wait for a socket at one time.'
@property def wait_queue_multiple(self):
return self.__wait_queue_multiple
'An SSLContext instance or None.'
@property def ssl_context(self):
return self.__ssl_context
'Call ssl.match_hostname if cert_reqs is not ssl.CERT_NONE.'
@property def ssl_match_hostname(self):
return self.__ssl_match_hostname
'Whether to send periodic messages to determine if a connection is closed.'
@property def socket_keepalive(self):
return self.__socket_keepalive
'An instance of pymongo.monitoring._EventListeners.'
@property def event_listeners(self):
return self.__event_listeners
'The application name, for sending with ismaster in server handshake.'
@property def appname(self):
return self.__appname
'A dict of metadata about the application, driver, os, and platform.'
@property def metadata(self):
return self.__metadata.copy()
'Execute a command or raise ConnectionFailure or OperationFailure. :Parameters: - `dbname`: name of the database on which to run the command - `spec`: a command document as a dict, SON, or mapping object - `slave_ok`: whether to set the SlaveOkay wire protocol bit - `read_preference`: a read preference - `codec_options`: a CodecOptions instance - `check`: raise OperationFailure if there are errors - `allowable_errors`: errors to ignore if `check` is True - `check_keys`: if True, check `spec` for invalid keys - `read_concern`: The read concern for this command. - `write_concern`: The write concern for this command. - `parse_write_concern_error`: Whether to parse the ``writeConcernError`` field in the command response. - `collation`: The collation for this command.'
def command(self, dbname, spec, slave_ok=False, read_preference=ReadPreference.PRIMARY, codec_options=DEFAULT_CODEC_OPTIONS, check=True, allowable_errors=None, check_keys=False, read_concern=DEFAULT_READ_CONCERN, write_concern=None, parse_write_concern_error=False, collation=None):
if ((self.max_wire_version < 4) and (not read_concern.ok_for_legacy)): raise ConfigurationError(('read concern level of %s is not valid with a max wire version of %d.' % (read_concern.level, self.max_wire_version))) if (not ((write_concern is None) or write_concern.acknowledged or (collation is None))): raise ConfigurationError('Collation is unsupported for unacknowledged writes.') if ((self.max_wire_version >= 5) and write_concern): spec['writeConcern'] = write_concern.document elif ((self.max_wire_version < 5) and (collation is not None)): raise ConfigurationError('Must be connected to MongoDB 3.4+ to use a collation.') try: return command(self.sock, dbname, spec, slave_ok, self.is_mongos, read_preference, codec_options, check, allowable_errors, self.address, check_keys, self.listeners, self.max_bson_size, read_concern, parse_write_concern_error=parse_write_concern_error, collation=collation) except OperationFailure: raise except BaseException as error: self._raise_connection_failure(error)
'Send a raw BSON message or raise ConnectionFailure. If a network exception is raised, the socket is closed.'
def send_message(self, message, max_doc_size):
if ((self.max_bson_size is not None) and (max_doc_size > self.max_bson_size)): raise DocumentTooLarge(('BSON document too large (%d bytes) - the connected server supports BSON document sizes up to %d bytes.' % (max_doc_size, self.max_bson_size))) try: self.sock.sendall(message) except BaseException as error: self._raise_connection_failure(error)
'Receive a raw BSON message or raise ConnectionFailure. If any exception is raised, the socket is closed.'
def receive_message(self, operation, request_id):
try: return receive_message(self.sock, operation, request_id, self.max_message_size) except BaseException as error: self._raise_connection_failure(error)
'Send OP_INSERT, etc., optionally returning response as a dict. Can raise ConnectionFailure or OperationFailure. :Parameters: - `request_id`: an int. - `msg`: bytes, an OP_INSERT, OP_UPDATE, or OP_DELETE message, perhaps with a getlasterror command appended. - `max_doc_size`: size in bytes of the largest document in `msg`. - `with_last_error`: True if a getlasterror command is appended.'
def legacy_write(self, request_id, msg, max_doc_size, with_last_error):
if ((not with_last_error) and (not self.is_writable)): raise NotMasterError('not master') self.send_message(msg, max_doc_size) if with_last_error: response = self.receive_message(1, request_id) return helpers._check_gle_response(response)
'Send "insert" etc. command, returning response as a dict. Can raise ConnectionFailure or OperationFailure. :Parameters: - `request_id`: an int. - `msg`: bytes, the command message.'
def write_command(self, request_id, msg):
self.send_message(msg, 0) response = helpers._unpack_response(self.receive_message(1, request_id)) assert (response['number_returned'] == 1) result = response['data'][0] helpers._check_command_response(result) return result
'Update this socket\'s authentication. Log in or out to bring this socket\'s credentials up to date with those provided. Can raise ConnectionFailure or OperationFailure. :Parameters: - `all_credentials`: dict, maps auth source to MongoCredential.'
def check_auth(self, all_credentials):
if (all_credentials or self.authset): cached = set(itervalues(all_credentials)) authset = self.authset.copy() for credentials in (authset - cached): auth.logout(credentials.source, self) self.authset.discard(credentials) for credentials in (cached - authset): auth.authenticate(credentials, self) self.authset.add(credentials)
'Log in to the server and store these credentials in `authset`. Can raise ConnectionFailure or OperationFailure. :Parameters: - `credentials`: A MongoCredential.'
def authenticate(self, credentials):
auth.authenticate(credentials, self) self.authset.add(credentials)
':Parameters: - `address`: a (hostname, port) tuple - `options`: a PoolOptions instance - `handshake`: whether to call ismaster for each new SocketInfo'
def __init__(self, address, options, handshake=True):
self._check_interval_seconds = 1 self.sockets = set() self.lock = threading.Lock() self.active_sockets = 0 self.pool_id = 0 self.pid = os.getpid() self.address = address self.opts = options self.handshake = handshake if ((self.opts.wait_queue_multiple is None) or (self.opts.max_pool_size is None)): max_waiters = None else: max_waiters = (self.opts.max_pool_size * self.opts.wait_queue_multiple) self._socket_semaphore = thread_util.create_semaphore(self.opts.max_pool_size, max_waiters) self.socket_checker = SocketChecker()
'Connect to Mongo and return a new SocketInfo. Can raise ConnectionFailure or CertificateError. Note that the pool does not keep a reference to the socket -- you must call return_socket() when you\'re done with it.'
def connect(self):
sock = None try: sock = _configured_socket(self.address, self.opts) if self.handshake: cmd = SON([('ismaster', 1), ('client', self.opts.metadata)]) ismaster = IsMaster(command(sock, 'admin', cmd, False, False, ReadPreference.PRIMARY, DEFAULT_CODEC_OPTIONS)) else: ismaster = None return SocketInfo(sock, self, ismaster, self.address) except socket.error as error: if (sock is not None): sock.close() _raise_connection_failure(self.address, error)
'Get a socket from the pool. Use with a "with" statement. Returns a :class:`SocketInfo` object wrapping a connected :class:`socket.socket`. This method should always be used in a with-statement:: with pool.get_socket(credentials, checkout) as socket_info: socket_info.send_message(msg) data = socket_info.receive_message(op_code, request_id) The socket is logged in or out as needed to match ``all_credentials`` using the correct authentication mechanism for the server\'s wire protocol version. Can raise ConnectionFailure or OperationFailure. :Parameters: - `all_credentials`: dict, maps auth source to MongoCredential. - `checkout` (optional): keep socket checked out.'
@contextlib.contextmanager def get_socket(self, all_credentials, checkout=False):
sock_info = self._get_socket_no_auth() try: sock_info.check_auth(all_credentials) (yield sock_info) except: self.return_socket(sock_info) raise else: if (not checkout): self.return_socket(sock_info)
'Get or create a SocketInfo. Can raise ConnectionFailure.'
def _get_socket_no_auth(self):
if (self.pid != os.getpid()): self.reset() if (not self._socket_semaphore.acquire(True, self.opts.wait_queue_timeout)): self._raise_wait_queue_timeout() with self.lock: self.active_sockets += 1 try: try: with self.lock: sock_info = self.sockets.pop() except KeyError: sock_info = self.connect() else: sock_info = self._check(sock_info) except: self._socket_semaphore.release() with self.lock: self.active_sockets -= 1 raise return sock_info
'Return the socket to the pool, or if it\'s closed discard it.'
def return_socket(self, sock_info):
if (self.pid != os.getpid()): self.reset() elif (sock_info.pool_id != self.pool_id): sock_info.close() elif (not sock_info.closed): sock_info.last_checkin = _time() with self.lock: self.sockets.add(sock_info) self._socket_semaphore.release() with self.lock: self.active_sockets -= 1
'This side-effecty function checks if this socket has been idle for for longer than the max idle time, or if the socket has been closed by some external network error, and if so, attempts to create a new socket. If this connection attempt fails we raise the ConnectionFailure. Checking sockets lets us avoid seeing *some* :class:`~pymongo.errors.AutoReconnect` exceptions on server hiccups, etc. We only check if the socket was closed by an external error if it has been > 1 second since the socket was checked into the pool, to keep performance reasonable - we can\'t avoid AutoReconnects completely anyway.'
def _check(self, sock_info):
idle_time_seconds = (_time() - sock_info.last_checkin) if ((self.opts.max_idle_time_ms is not None) and ((idle_time_seconds * 1000) > self.opts.max_idle_time_ms)): sock_info.close() return self.connect() if ((self._check_interval_seconds is not None) and ((0 == self._check_interval_seconds) or (idle_time_seconds > self._check_interval_seconds))): if self.socket_checker.socket_closed(sock_info.sock): sock_info.close() return self.connect() return sock_info
'The document representation of this write concern. .. note:: :class:`WriteConcern` is immutable. Mutating the value of :attr:`document` does not mutate this :class:`WriteConcern`.'
@property def document(self):
return self.__document.copy()
'If ``True`` write operations will wait for acknowledgement before returning.'
@property def acknowledged(self):
return self.__acknowledged
'Return a find command document for this query. Should be called *after* get_message.'
def as_command(self):
if ('$explain' in self.spec): self.name = 'explain' return (_gen_explain_command(self.coll, self.spec, self.fields, self.ntoskip, self.limit, self.batch_size, self.flags, self.read_concern), self.db) return (_gen_find_command(self.coll, self.spec, self.fields, self.ntoskip, self.limit, self.batch_size, self.flags, self.read_concern, self.collation), self.db)
'Get a query message, possibly setting the slaveOk bit.'
def get_message(self, set_slave_ok, is_mongos, use_cmd=False):
if set_slave_ok: flags = (self.flags | 4) else: flags = self.flags ns = (_UJOIN % (self.db, self.coll)) spec = self.spec if use_cmd: ns = (_UJOIN % (self.db, '$cmd')) spec = self.as_command()[0] ntoreturn = (-1) else: ntoreturn = (((self.batch_size == 1) and 2) or self.batch_size) if self.limit: if ntoreturn: ntoreturn = min(self.limit, ntoreturn) else: ntoreturn = self.limit if is_mongos: spec = _maybe_add_read_preference(spec, self.read_preference) return query(flags, ns, self.ntoskip, ntoreturn, spec, self.fields, self.codec_options)
'Return a getMore command document for this query.'
def as_command(self):
return (_gen_get_more_command(self.cursor_id, self.coll, self.ntoreturn, self.max_await_time_ms), self.db)
'Get a getmore message.'
def get_message(self, dummy0, dummy1, use_cmd=False):
ns = (_UJOIN % (self.db, self.coll)) if use_cmd: ns = (_UJOIN % (self.db, '$cmd')) spec = self.as_command()[0] return query(0, ns, 0, (-1), spec, None, self.codec_options) return get_more(ns, self.ntoreturn, self.cursor_id)
'The namespace this cursor.'
@property def namespace(self):
return self.__namespace
'A proxy for SockInfo.max_bson_size.'
@property def max_bson_size(self):
return self.sock_info.max_bson_size
'A proxy for SockInfo.max_message_size.'
@property def max_message_size(self):
return self.sock_info.max_message_size
'A proxy for SockInfo.max_write_batch_size.'
@property def max_write_batch_size(self):
return self.sock_info.max_write_batch_size
'A proxy for SocketInfo.legacy_write that handles event publishing.'
def legacy_write(self, request_id, msg, max_doc_size, acknowledged, docs):
if self.publish: duration = (datetime.datetime.now() - self.start_time) cmd = self._start(request_id, docs) start = datetime.datetime.now() try: result = self.sock_info.legacy_write(request_id, msg, max_doc_size, acknowledged) if self.publish: duration = ((datetime.datetime.now() - start) + duration) if (result is not None): reply = _convert_write_result(self.name, cmd, result) else: reply = {'ok': 1} self._succeed(request_id, reply, duration) except OperationFailure as exc: if self.publish: duration = ((datetime.datetime.now() - start) + duration) self._fail(request_id, _convert_write_result(self.name, cmd, exc.details), duration) raise finally: self.start_time = datetime.datetime.now() return result
'A proxy for SocketInfo.write_command that handles event publishing.'
def write_command(self, request_id, msg, docs):
if self.publish: duration = (datetime.datetime.now() - self.start_time) self._start(request_id, docs) start = datetime.datetime.now() try: reply = self.sock_info.write_command(request_id, msg) if self.publish: duration = ((datetime.datetime.now() - start) + duration) self._succeed(request_id, reply, duration) except OperationFailure as exc: if self.publish: duration = ((datetime.datetime.now() - start) + duration) self._fail(request_id, exc.details, duration) raise finally: self.start_time = datetime.datetime.now() return reply
'Publish a CommandStartedEvent.'
def _start(self, request_id, docs):
cmd = self.command.copy() cmd[self.field] = docs self.listeners.publish_command_start(cmd, self.db_name, request_id, self.sock_info.address, self.op_id) return cmd
'Publish a CommandSucceededEvent.'
def _succeed(self, request_id, reply, duration):
self.listeners.publish_command_success(duration, reply, self.name, request_id, self.sock_info.address, self.op_id)
'Publish a CommandFailedEvent.'
def _fail(self, request_id, failure, duration):
self.listeners.publish_command_failure(duration, failure, self.name, request_id, self.sock_info.address, self.op_id)
'The read concern level.'
@property def level(self):
return self.__level
'Return ``True`` if this read concern is compatible with old wire protocol versions.'
@property def ok_for_legacy(self):
return ((self.level is None) or (self.level == 'local'))
'The document representation of this read concern. .. note:: :class:`ReadConcern` is immutable. Mutating the value of :attr:`document` does not mutate this :class:`ReadConcern`.'
@property def document(self):
doc = {} if self.__level: doc['level'] = self.level return doc
'Class to monitor a MongoDB server on a background thread. Pass an initial ServerDescription, a Topology, a Pool, and TopologySettings. The Topology is weakly referenced. The Pool must be exclusive to this Monitor.'
def __init__(self, server_description, topology, pool, topology_settings):
self._server_description = server_description self._pool = pool self._settings = topology_settings self._avg_round_trip_time = MovingAverage() self._listeners = self._settings._pool_options.event_listeners pub = (self._listeners is not None) self._publish = (pub and self._listeners.enabled_for_server_heartbeat) def target(): monitor = self_ref() if (monitor is None): return False Monitor._run(monitor) return True executor = periodic_executor.PeriodicExecutor(interval=self._settings.heartbeat_frequency, min_interval=common.MIN_HEARTBEAT_INTERVAL, target=target, name='pymongo_server_monitor_thread') self._executor = executor self_ref = weakref.ref(self, executor.close) self._topology = weakref.proxy(topology, executor.close)
'Start monitoring, or restart after a fork. Multiple calls have no effect.'
def open(self):
self._executor.open()
'Close and stop monitoring. open() restarts the monitor after closing.'
def close(self):
self._executor.close() self._pool.reset()