简体   繁体   中英

pymongo 3.2: ConnectionFailure not working

I'm pulling my hair out trying to get pymongo to error out when code can't connect to a MongoD instance. It seems like no matter what I do the 'pymongo.errors.ConnectionFailure' is not working. I've tried this on localhost and a remote mongoD instance. When I use the mongoclient shell ('mongo --host xx.xx.xx.xx') from the same system, I get the proper 'connection refused'. Other exceptions are working, but not 'ConnectionFailure.' Note that when I run tshark sniffer on mongod instance host, I see the proper TCP RST on closed port for connection refused. Mongod is not listening, but the pymongo ConnectionFailure can't catch a failed connection.

python version: 2.7.10 pymongo version: 3.2

What could I be missing, or steps to troubleshoot? In this example below, mongod is not running on localhost. I also stop it on remote host. In both instances, the exception error is not caught, and pymongo code appears to think it is connected.

Code:

import pymongo
try:
    pymongo.MongoClient('localhost:27017')
except pymongo.errors.ConnectionFailure, e:
    print "Could not connect: %s" % e
def dbConnect():
    try:
        conn = pymongo.MongoClient(<connection URL>)
        try:
            conn.server_info()
            return "Connection Successfull"
        except OperationFailure as e:
            return e
    except Exception as e:
        return e

print (dbConnect())

As MongoClient Doesn't return a valuable response that can help in connectin state this will work just fine.

I am also facing this problem while using pymongo.MongoClient() .

Try this code below, it might help you:

def initiateDbConnection():
        try:
            dbConnection= pymongo.MongoClient(<connection URL>)
            try:
                dbConnection.server_info()
                return "Connection Established"
            except OperationFailure as err:
                return err
        except Exception as err:
            return err
    print (initiateDbConnection())

First attempt: Syntax error

You got an syntax error in your code. Change:

pymongo.MongoClient('localhost':27017)

into:

pymongo.MongoClient('localhost:27017')

or something like this:

pymongo.MongoClient(host='localhost', port=27017)

You had the single quote at the wrong place.


Working sample snippet using Python 3.4.3 and pymongo 2.9

import pymongo

try:
    pymongo.MongoClient('localhost:27017')
except pymongo.errors.ConnectionFailure as e:
    print(e)

After reading the Pymongo3 migration guide

I think this behaviour is as desired since the guide tells:

In PyMongo 3, the MongoClient constructor no longer blocks while connecting to the server or servers, and it no longer raises ConnectionFailure if they are unavailable, nor ConfigurationError if the user's credentials are wrong. Instead, the constructor returns immediately and launches the connection process on background threads. The connect option is added to control whether these threads are started immediately, or when the client is first used.

As shown in the migration guide something like this should work:

 from pymongo.errors import ConnectionFailure client = MongoClient(connect=False) try: result = client.admin.command("ismaster") except ConnectionFailure: print("Server not available")

This seems to work only when I add two more lines to get the database and authenticate. I don't know why. Shouldn't ConnectionFailure catch the error only when you try to connect?

try:
    dbconn = pymongo.MongoClient(host, port)
    db = dbconn[dbname]
    success = db.authenticate(user, password)

except pymongo.errors.ConnectionFailure as msg:
    print "Failed connection: %s" % str(msg)

When I watch this with a sniffer on a host that isn't running mongod, it attempts to connect for 20-30 seconds, and then the pymongo host prints:

'Failed connection: host.db.com:27017: [Errno 61] Connection refused'

For those who come in the future, this is how we solved our issue with this error, after a day of troubleshooting

I have a Flask project, connecting to MongoDb using Python 3.9.6, pymongo 3.12.0, flask 2.0.1, and flask-pymongo 2.3.0.

My connection string looked like this: mongodb+srv://my_username:my_user@cluster0.abc123.mongodb.net/my_db_name?retryWrites=true&w=majority

My initialization of the connection in app.py looked like this:

    app.config["MONGO_URI"] = "mongodb+srv://my_username:my_user@cluster0.abc123.mongodb.net/my_db_name?retryWrites=true&w=majority"
    mongo = PyMongo(app)
    db = mongo.db
    print("db initialization complete")

After trying to read or write to the DB without success, yet receiving no errors, I added a try/except like this:

try:
            myCollection = db["collectionName"]
            result = myCollection.find({}) # returns all documents
            print("after query", result)
            print("after query, again", list(result))
        except Exception as err:
            print("Error in query_db -> ", err)

I was then able to see the error that was occurring. It was a timeout due to a connection failure.

Error in query_db -> cluster0.nt7lk.mongodb.net:27017: [Errno 11001] getaddrinfo failed, Timeout: 30s, Topology Description: <TopologyDescription id: 6124a7768a437d2f7c01cdcf, topology_type: Single, servers: [<ServerDescription ('cluster0.nt7lk.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('cluster0.nt7lk.mongodb.net:27017: [Errno 11001] getaddrinfo failed')>]>

After spending another hour trying to figure this out, including checking the open IP address and port on the Mongo Compass web portal, making sure the connection string came from the 'Connect via Application' instead of 'Connect via Mongo Compass', and a thousand ways of defining the initialization, I realized that I needed the dnspython package in order to use mongo connection strings that include srv in them.

Run pip install -r dnspython to install it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM