您如何检查 MongoDB 实例的客户端是否有效?
How do you check if the client for a MongoDB instance is valid?
特别是,我目前正在尝试使用以下函数检查与客户端的连接是否有效:
def mongodb_connect(client_uri):
try:
return pymongo.MongoClient(client_uri)
except pymongo.errors.ConnectionFailure:
print "Failed to connect to server {}".format(client_uri)
然后我像这样使用这个函数:
def bucket_summary(self):
client_uri = "some_client_uri"
client = mongodb_connect(client_uri)
db = client[tenant_id]
ttb = db.timebucket.count() # If I use an invalid URI it hangs here
如果给出了无效的 URI,有没有办法在最后一行捕获并抛出异常?我最初认为这就是 ConnectionFailure 的用途(因此在连接时可能会被捕获)但我错了。
如果我 运行 具有无效 URI 的程序无法 运行,发出 KeyboardInterrupt 会产生:
File "reportjob_status.py", line 58, in <module>
tester.summarize_timebuckets()
File "reportjob_status.py", line 43, in summarize_timebuckets
ttb = db.timebucket.count() #error
File "/Library/Python/2.7/site-packages/pymongo/collection.py", line 1023, in count
return self._count(cmd)
File "/Library/Python/2.7/site-packages/pymongo/collection.py", line 985, in _count
with self._socket_for_reads() as (sock_info, slave_ok):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/contextlib.py", line 17, in __enter__
return self.gen.next()
File "/Library/Python/2.7/site-packages/pymongo/mongo_client.py", line 699, in _socket_for_reads
with self._get_socket(read_preference) as sock_info:
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/contextlib.py", line 17, in __enter__
return self.gen.next()
File "/Library/Python/2.7/site-packages/pymongo/mongo_client.py", line 663, in _get_socket
server = self._get_topology().select_server(selector)
File "/Library/Python/2.7/site-packages/pymongo/topology.py", line 121, in select_server
address))
File "/Library/Python/2.7/site-packages/pymongo/topology.py", line 106, in select_servers
self._condition.wait(common.MIN_HEARTBEAT_INTERVAL)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 358, in wait
_sleep(delay)
pymongo.mongo_client.MongoClient
的 serverSelectionTimeoutMS
关键字参数控制驱动程序尝试连接服务器的时间。默认值为 30s。
将其设置为与您的典型连接时间兼容的非常低的值¹,以立即报告错误。之后您需要查询数据库以触发连接尝试:
>>> maxSevSelDelay = 1 # Assume 1ms maximum server selection delay
>>> client = pymongo.MongoClient("someInvalidURIOrNonExistantHost",
serverSelectionTimeoutMS=maxSevSelDelay)
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>>> client.server_info()
这将提高 pymongo.errors.ServerSelectionTimeoutError
。
¹ 显然 将 serverSelectionTimeoutMS
设置为 0
甚至可能在您的服务器延迟非常低的特定情况下工作(例如例如负载很轻的 "local" 服务器)
捕获异常并正确处理它取决于您。 喜欢的东西:
try:
client = pymongo.MongoClient("someInvalidURIOrNonExistantHost",
serverSelectionTimeoutMS=maxSevSelDelay)
client.server_info() # force connection on a request as the
# connect=True parameter of MongoClient seems
# to be useless here
except pymongo.errors.ServerSelectionTimeoutError as err:
# do whatever you need
print(err)
将显示:
No servers found yet
您好,要确定连接是否已建立,您可以这样做:
from pymongo import MongoClient
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")
serverSelectionTimeoutMS
This defines how long to block for server selection before throwing an
exception. The default is 30,000 (milliseconds). It MUST be
configurable at the client level. It MUST NOT be configurable at the
level of a database object, collection object, or at the level of an
individual query.
This default value was chosen to be sufficient for a typical server
primary election to complete. As the server improves the speed of
elections, this number may be revised downward.
Users that can tolerate long delays for server selection when the
topology is in flux can set this higher. Users that want to "fail
fast" when the topology is in flux can set this to a small number.
A serverSelectionTimeoutMS of zero MAY have special meaning in some
drivers; zero's meaning is not defined in this spec, but all drivers
SHOULD document the meaning of zero.
# pymongo 3.5.1
from pymongo import MongoClient
from pymongo.errors import ServerSelectionTimeoutError
client = MongoClient("mongodb://localhost:27000/", serverSelectionTimeoutMS=10, connectTimeoutMS=20000)
try:
info = client.server_info() # Forces a call.
except ServerSelectionTimeoutError:
print("server is down.")
# If connection create a new one with serverSelectionTimeoutMS=30000
serverSelectionTimeoutMS
对我不起作用(Python 2.7.12,MongoDB 3.6.1,pymongo 3.6.0)。 A. Jesse Jiryu Davis suggested in a GitHub issue 我们首先尝试套接字级连接作为试金石。这对我有用。
def throw_if_mongodb_is_unavailable(host, port):
import socket
sock = None
try:
sock = socket.create_connection(
(host, port),
timeout=1) # one second
except socket.error as err:
raise EnvironmentError(
"Can't connect to MongoDB at {host}:{port} because: {err}"
.format(**locals()))
finally:
if sock is not None:
sock.close()
# elsewhere...
HOST = 'localhost'
PORT = 27017
throw_if_mongodb_is_unavailable(HOST, PORT)
import pymongo
conn = pymongo.MongoClient(HOST, PORT)
print(conn.admin.command('ismaster'))
# etc.
有很多问题这不会发现,但如果服务器不 运行 或无法访问,这会立即显示给您。
也可以这样检查:
from pymongo import MongoClient
from pymongo.errors import OperationFailure
def check_mongo_connection(client_uri):
connection = MongoClient(client_uri)
try:
connection.database_names()
print('Data Base Connection Established........')
except OperationFailure as err:
print(f"Data Base Connection failed. Error: {err}")
check_mongo_connection(client_uri)
特别是,我目前正在尝试使用以下函数检查与客户端的连接是否有效:
def mongodb_connect(client_uri):
try:
return pymongo.MongoClient(client_uri)
except pymongo.errors.ConnectionFailure:
print "Failed to connect to server {}".format(client_uri)
然后我像这样使用这个函数:
def bucket_summary(self):
client_uri = "some_client_uri"
client = mongodb_connect(client_uri)
db = client[tenant_id]
ttb = db.timebucket.count() # If I use an invalid URI it hangs here
如果给出了无效的 URI,有没有办法在最后一行捕获并抛出异常?我最初认为这就是 ConnectionFailure 的用途(因此在连接时可能会被捕获)但我错了。
如果我 运行 具有无效 URI 的程序无法 运行,发出 KeyboardInterrupt 会产生:
File "reportjob_status.py", line 58, in <module>
tester.summarize_timebuckets()
File "reportjob_status.py", line 43, in summarize_timebuckets
ttb = db.timebucket.count() #error
File "/Library/Python/2.7/site-packages/pymongo/collection.py", line 1023, in count
return self._count(cmd)
File "/Library/Python/2.7/site-packages/pymongo/collection.py", line 985, in _count
with self._socket_for_reads() as (sock_info, slave_ok):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/contextlib.py", line 17, in __enter__
return self.gen.next()
File "/Library/Python/2.7/site-packages/pymongo/mongo_client.py", line 699, in _socket_for_reads
with self._get_socket(read_preference) as sock_info:
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/contextlib.py", line 17, in __enter__
return self.gen.next()
File "/Library/Python/2.7/site-packages/pymongo/mongo_client.py", line 663, in _get_socket
server = self._get_topology().select_server(selector)
File "/Library/Python/2.7/site-packages/pymongo/topology.py", line 121, in select_server
address))
File "/Library/Python/2.7/site-packages/pymongo/topology.py", line 106, in select_servers
self._condition.wait(common.MIN_HEARTBEAT_INTERVAL)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 358, in wait
_sleep(delay)
pymongo.mongo_client.MongoClient
的 serverSelectionTimeoutMS
关键字参数控制驱动程序尝试连接服务器的时间。默认值为 30s。
将其设置为与您的典型连接时间兼容的非常低的值¹,以立即报告错误。之后您需要查询数据库以触发连接尝试:
>>> maxSevSelDelay = 1 # Assume 1ms maximum server selection delay
>>> client = pymongo.MongoClient("someInvalidURIOrNonExistantHost",
serverSelectionTimeoutMS=maxSevSelDelay)
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>>> client.server_info()
这将提高 pymongo.errors.ServerSelectionTimeoutError
。
¹ 显然 将 serverSelectionTimeoutMS
设置为 0
甚至可能在您的服务器延迟非常低的特定情况下工作(例如例如负载很轻的 "local" 服务器)
捕获异常并正确处理它取决于您。 喜欢的东西:
try:
client = pymongo.MongoClient("someInvalidURIOrNonExistantHost",
serverSelectionTimeoutMS=maxSevSelDelay)
client.server_info() # force connection on a request as the
# connect=True parameter of MongoClient seems
# to be useless here
except pymongo.errors.ServerSelectionTimeoutError as err:
# do whatever you need
print(err)
将显示:
No servers found yet
您好,要确定连接是否已建立,您可以这样做:
from pymongo import MongoClient
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")
serverSelectionTimeoutMS
This defines how long to block for server selection before throwing an exception. The default is 30,000 (milliseconds). It MUST be configurable at the client level. It MUST NOT be configurable at the level of a database object, collection object, or at the level of an individual query.
This default value was chosen to be sufficient for a typical server primary election to complete. As the server improves the speed of elections, this number may be revised downward.
Users that can tolerate long delays for server selection when the topology is in flux can set this higher. Users that want to "fail fast" when the topology is in flux can set this to a small number.
A serverSelectionTimeoutMS of zero MAY have special meaning in some drivers; zero's meaning is not defined in this spec, but all drivers SHOULD document the meaning of zero.
# pymongo 3.5.1
from pymongo import MongoClient
from pymongo.errors import ServerSelectionTimeoutError
client = MongoClient("mongodb://localhost:27000/", serverSelectionTimeoutMS=10, connectTimeoutMS=20000)
try:
info = client.server_info() # Forces a call.
except ServerSelectionTimeoutError:
print("server is down.")
# If connection create a new one with serverSelectionTimeoutMS=30000
serverSelectionTimeoutMS
对我不起作用(Python 2.7.12,MongoDB 3.6.1,pymongo 3.6.0)。 A. Jesse Jiryu Davis suggested in a GitHub issue 我们首先尝试套接字级连接作为试金石。这对我有用。
def throw_if_mongodb_is_unavailable(host, port):
import socket
sock = None
try:
sock = socket.create_connection(
(host, port),
timeout=1) # one second
except socket.error as err:
raise EnvironmentError(
"Can't connect to MongoDB at {host}:{port} because: {err}"
.format(**locals()))
finally:
if sock is not None:
sock.close()
# elsewhere...
HOST = 'localhost'
PORT = 27017
throw_if_mongodb_is_unavailable(HOST, PORT)
import pymongo
conn = pymongo.MongoClient(HOST, PORT)
print(conn.admin.command('ismaster'))
# etc.
有很多问题这不会发现,但如果服务器不 运行 或无法访问,这会立即显示给您。
也可以这样检查:
from pymongo import MongoClient
from pymongo.errors import OperationFailure
def check_mongo_connection(client_uri):
connection = MongoClient(client_uri)
try:
connection.database_names()
print('Data Base Connection Established........')
except OperationFailure as err:
print(f"Data Base Connection failed. Error: {err}")
check_mongo_connection(client_uri)