0 votes
1 view
in Python by (11.8k points)

Specifically, I am at present attempting to check if a connection with a customer is valid utilizing the accompanying function: 

def mongodb_connect(client_uri):

    try:

        return pymongo.MongoClient(client_uri)

    except pymongo.errors.ConnectionFailure:

         print "Failed to connect to server {}".format(client_uri)

Then I utilized this function like this: 

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

Is there an approach to catch and throws an exception at last line incase if an invalid URI is given? I at first imagined that is the thing that the ConnectionFailure was for (so this could be found while connecting) however I wasn't right.

On the off chance that I execute the program with an invalid URI, which neglects to run, giving a KeyboardInterrupt yields: 

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)

1 Answer

0 votes
by (24.6k points)

The serverSelectionTimeoutMS keyword boundary of pymongo.mongo_client.MongoClient controls how long the driver will attempt to associate with a server. The default esteem is 30s.

Set it to a low worth viable with your regular connection time to quickly report an error. You need to inquiry the DB after that to trigger an association attempt : 

>>> maxSevSelDelay = 1 # Assume 1ms maximum server selection delay

>>> client = pymongo.MongoClient("someInvalidURIOrNonExistantHost",

                                 serverSelectionTimeoutMS=maxSevSelDelay)

//                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

>>> client.server_info()

This raised pymongo.errors.ServerSelectionTimeoutError.

It is dependent upon you to get that exception and to deal with it appropriately. Something to that effect:

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)

which will display:

No servers found yet.

Want to become a expert in Python? Join the python course fast!

Related questions

0 votes
1 answer
0 votes
1 answer
asked Feb 14, 2020 in Web Technology by ashely (50.5k points)
0 votes
2 answers
asked Sep 4, 2019 in SQL by Sammy (47.8k points)
0 votes
1 answer
0 votes
2 answers
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...