pymongo==3.0.3: ImportError: No module named conne

2019-08-13 14:51发布

问题:

I just upgraded to pymongo==3.0.3 via pip install --upgrade pymongo, and I'm flooded with ImportError:

In [2]: pymongo.version
Out[2]: '3.0.3'

In [3]: from pymongo import Connection
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-3-dd44bc3249d3> in <module>()
----> 1 from pymongo import Connection

ImportError: cannot import name Connection

In [4]: from pymongo import connection
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-4-71c9e4ec1bcd> in <module>()
----> 1 from pymongo import connection

ImportError: cannot import name connection

In [5]: import pymongo.connection.Connection
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-5-282b89157c85> in <module>()
----> 1 import pymongo.connection.Connection

ImportError: No module named connection.Connection

回答1:

According to Pymongo 3.0 changelog -

MongoClient changes

MongoClient is now the one and only client class for a standalone server, mongos, or replica set. It includes the functionality that had been split into MongoReplicaSetClient: it can connect to a replica set, discover all its members, and monitor the set for stepdowns, elections, and reconfigs. MongoClient now also supports the full ReadPreference API.

The obsolete classes MasterSlaveConnection, Connection, and ReplicaSetConnection are removed.

As you can see Connection class has been removed from pymonge 3.0 , try using MongoClient instead. Information about mongoclient can be found here



回答2:

Probably you can support both versions in your code by doing something like this.

try:
    from pymongo.connection import Connection
except ImportError as e:
    from pymongo import MongoClient as Connection


回答3:

Since Connection class is deprecated from pymongo(3.0.0). Install a older version of pymongo(2.9) to make it temporarily work. It can be done with pip using:

pip install  pymongo==2.9