| 172 | |
| 173 | |
| 174 | class MongoClient(common.BaseObject, Generic[_DocumentType]): |
| 175 | HOST = "localhost" |
| 176 | PORT = 27017 |
| 177 | # Define order to retrieve options from ClientOptions for __repr__. |
| 178 | # No host/port; these are retrieved from TopologySettings. |
| 179 | _constructor_args = ("document_class", "tz_aware", "connect") |
| 180 | _clients: weakref.WeakValueDictionary = weakref.WeakValueDictionary() # type: ignore[type-arg] |
| 181 | |
| 182 | def __init__( |
| 183 | self, |
| 184 | host: Optional[Union[str, Sequence[str]]] = None, |
| 185 | port: Optional[int] = None, |
| 186 | document_class: Optional[Type[_DocumentType]] = None, |
| 187 | tz_aware: Optional[bool] = None, |
| 188 | connect: Optional[bool] = None, |
| 189 | type_registry: Optional[TypeRegistry] = None, |
| 190 | **kwargs: Any, |
| 191 | ) -> None: |
| 192 | """Client for a MongoDB instance, a replica set, or a set of mongoses. |
| 193 | |
| 194 | .. warning:: Starting in PyMongo 4.0, ``directConnection`` now has a default value of |
| 195 | False instead of None. |
| 196 | For more details, see the relevant section of the PyMongo 4.x migration guide: |
| 197 | :ref:`pymongo4-migration-direct-connection`. |
| 198 | |
| 199 | The client object is thread-safe and has connection-pooling built in. |
| 200 | If an operation fails because of a network error, |
| 201 | :class:`~pymongo.errors.ConnectionFailure` is raised and the client |
| 202 | reconnects in the background. Application code should handle this |
| 203 | exception (recognizing that the operation failed) and then continue to |
| 204 | execute. |
| 205 | |
| 206 | Best practice is to call :meth:`MongoClient.close` when the client is no longer needed, |
| 207 | or use the client in a with statement:: |
| 208 | |
| 209 | with MongoClient(url) as client: |
| 210 | # Use client here. |
| 211 | |
| 212 | The `host` parameter can be a full `mongodb URI |
| 213 | <https://dochub.mongodb.org/core/connections>`_, in addition to |
| 214 | a simple hostname. It can also be a list of hostnames but no more |
| 215 | than one URI. Any port specified in the host string(s) will override |
| 216 | the `port` parameter. For username and |
| 217 | passwords reserved characters like ':', '/', '+' and '@' must be |
| 218 | percent encoded following RFC 2396:: |
| 219 | |
| 220 | from urllib.parse import quote_plus |
| 221 | |
| 222 | uri = "mongodb://%s:%s@%s" % ( |
| 223 | quote_plus(user), quote_plus(password), host) |
| 224 | client = MongoClient(uri) |
| 225 | |
| 226 | Unix domain sockets are also supported. The socket path must be percent |
| 227 | encoded in the URI:: |
| 228 | |
| 229 | uri = "mongodb://%s:%s@%s" % ( |
| 230 | quote_plus(user), quote_plus(password), quote_plus(socket_path)) |
| 231 | client = MongoClient(uri) |
no outgoing calls