It seems that a pymongo 4.10 async client does not raise an exception when there is a problem with the connection.
Taken from the doc, a test without any mongo DB running locally yields:
>>> import asyncio
>>> from pymongo import AsyncMongoClient
>>> client = AsyncMongoClient('mongodb://localhost:27017/')
>>> asyncio.run(client.aconnect())
# no errors
When activating debug logs I see the connection being refused but I would expect an exception to be raised.
>>> import logging
>>> logging.basicConfig(level='DEBUG')
>>> asyncio.run(client.aconnect())
DEBUG:asyncio:Using selector: KqueueSelector
DEBUG:pymongo.topology:{"topologyId": {"$oid": "676020be62e71d3fe6f27721"}, "serverHost": "localhost", "serverPort": 27017, "awaited": false, "durationMS": 2.786167000522255, "failure": "\"AutoReconnect('localhost:27017: [Errno 61] Connection refused (configured timeouts: socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms)')\"", "message": "Server heartbeat failed"}
I would expect the DEBUG log error to be an exception. Am I misunderstanding something with the async client ?
The mongo client uses connection pools etc in the background, even though you tell it to explicitly connect (why?) it doesn't raise an exception for failing to connect until you actually try to read or write from/to the DB.
But you can check if/where it's connected:
>>> list(client.nodes)
[('10.0.0.1', 27017)]
The result will be an empty list if aconnect
fails.
But if you try any communication such as:
>>> await client.server_info()
... you will get an exception:
pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused (configured timeouts: socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms), Timeout: 1.9985503089847043s, Topology Description: <TopologyDescription id: 6760281eda9a9980ea35e425, topology_type: Unknown, servers: [<ServerDescription ('localhost', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('localhost:27017: [Errno 111] Connection refused (configured timeouts: socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms)')>]>
The pymongo async driver is just built like this.. why the tutorial tells you to use aconnect()
... I have no idea. I didn't even know it existed.
Btw, you can use python -m async
to get a REPL where you can run async commands without asyncio.run()