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: [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

How can I fix this?


Submit an answer
You can type!ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Hey There!

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:

client = MongoClient(host, port)
db_name = 'foo'

def getdb():
        return getattr(client, db_name)
    except pymongo.errors.AutoReconnect as e:
        global client 
        print('Recreating mongo client to {}:{} {}'.format(host, port, e))
        client = MongoClient(host, port)
        return getattr(client, db_name)

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.

Hope that helps!