Problems with mongodb and flask

Hello I am having problems with my mongo instance that always give me this error after a leave the system up for a few moments:
pymongo.errors.AutoReconnect
pymongo.errors.AutoReconnect: 209.97.153.183:29642: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

Leave a Comment

It sounds like your Python Flask app is failing when trying to refresh the connection after a bit. It is tough to know why this could be happening without more info, but here are some things to check out.

Be sure any database config variables are still set correctly.

If you pass in a map as your configuration and that map changes (maps are mutable!) then when it initially connects, it may have the correct address. But if that changes, then when it tries to reconnect, the address might not be correct. For example:

client = MongoClient(app.config['DB'], 27107)
// later in the code
app.config.update(some_map) // <- this might have a `DB` value of ''!

There are a few Flask / MongoDB libs out there, so you’ll want to double check that the variables aren’t getting reset somehow.

Debug the connection with some prints

Another thing to try might be to create a wrapper around how you access the DB that will try to manually reconnect. For example:

This code might not be correct, but hopefully it conveys how you can try to double check your config.

Verify transport is working

If you get the error on your app host, make sure you can do some basic tasks like ping the DB host and connect using the MnogoDB client. If things look correct, check the logs on the MongoDB host as well to verify you see connection requests as well.

If you are using one of the specific Flask MongoDB libraries, it can be a good idea to search the project’s issue tracker on github for the error. Someone might have had a similar problem and gotten help there.