我正在尝试实施MongoDB连接处理程序,但遇到Database调用返回None
的问题,即使我的MongoClient()
调用成功。< / p>
#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)
失败的原因。
答案 0 :(得分:1)
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()
我不知道你在做什么是你应该做的事情