我正在尝试实现MongoDB连接处理程序,但是遇到一个问题,即使我的None调用成功,我的Database调用也会返回MongoClient()

#mongoconn.py

from pymongo import MongoClient
from pymongo.database import Database

class MongoConnection():
    mongoconn = None

    def __init__(self, db=None, collection=None, endpoint=None):
        self.mongodb = db
        self.mongocollection = collection
        self.mongoendpoint = endpoint
        mongoconn = self.__mongo_connect()

    def __mongo_connect(self):
        if self.mongoendpoint is not None:
            mc = MongoClient(host=self.mongoendpoint, port=27017, document_class=dict, tz_aware=False, connect=True)
            print mc    #successful object
            return Database(mc)
        else:
            mc = MongoClient(host='localhost', port=27017, document_class=dict, tz_aware=False, connect=True)
            print mc    #successful object
            return Database(mc, self.mongodb)

m1 = MongoConnection("torbot")

print m1.mongoconn    # None


我可以看到该集合torbot确实存在,所以我不认为这是问题所在:

MongoDB shell version v3.4.0
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.0
use torbot
switched to db torbot
db.requests.find();
{ "_id" : ObjectId("584f7e17bc1d1b7f37d54756"), "requestor" : "ctote", "request" : "Scott Pilgrim Vs The World" }


但是我找不到任何调试选项来查看为什么Database(mc, self.mongodb)调用失败的原因。

最佳答案

mongoconn是要在__init__方法中访问它的类属性,您需要在其前面加上类名或self。在您的情况下,您正在执行self.mongoconn将创建一个实例属性,该属性可能不是您想要的,因此您需要的是MongoConnection.mongoconn = self.__mongo_connect()。您的__init__方法变为:

class MongoConnection():
    mongoconn = None

    def __init__(self, db=None, collection=None, endpoint=None):
        self.mongodb = db
        self.mongocollection = collection
        self.mongoendpoint = endpoint
        MongoConnection.mongoconn = self.__mongo_connect()


我不知道你在做什么是否应该做

07-28 08:04