Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible for a MongoDB connection to timeout in Python?

(Newbie question, sorry about that -I'm just beginning with MongoDB)

I am connecting to mongo on heroku like this:

self.connection = pymongo.Connection(MONGO_URL)
self.db = self.connection.app13805318

Is it possible that I try to use self.db after a few hours and can't read it? Do I need to do some kind of keepalive or refresh of the connection?

like image 682
Avi Meir Avatar asked Jul 17 '13 14:07

Avi Meir


People also ask

What is connection timeout in MongoDB?

The connection timeout determines the maximum amount of response time that waits for a connection established by the server. This value is used when making an initial connection to the MongoDB database. The default connection timeout value ranges from 1 second to 30 seconds. For example, if you have the connection timeout set to 30 seconds, ...

What to do when MongoDB client takes too long to connect?

When the client takes too much time to connect to MongodB server than the preset timeout value, it can result in error. And the fix involves in raising the timeout limits on the MongoDB client. For this, we first check with the customer on the settings that they use on their client.

How to deploy MongoDB in Python?

Deployment of MongoDB is very easy. See port number by default is set 27017 (last line in above image). Python has a native library for MongoDB. The name of the available library is “PyMongo”. To import this, execute the following command: Create a connection : The very first after importing the module is to create a MongoClient.

What is pymongo for MongoDB?

PyMongo, the standard MongoDB driver library for Python, is easy to use and offers an intuitive API for accessing databases, collections, and documents. Objects retrieved from MongoDB through PyMongo are compatible with dictionaries and lists, so we can easily manipulate, iterate, and print them.


1 Answers

Citing from Pymongo documentation: https://pymongo.readthedocs.io/en/stable/api/pymongo/mongo_client.html#pymongo.mongo_client.MongoClient

The client object is thread-safe and has connection-pooling built in. If an operation fails because of a network error, 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.

So as @james-wahlin suggested in comments, you should not solely rely on pymongo's connection-pooling mechanism but always wrap your usage of self.db in try..except clauses.

Hope this helps.

like image 112
woozyking Avatar answered Nov 01 '22 10:11

woozyking