Reputation: 18282
I'm trying to implement a MongoDB connection handler, but am running into an issue where my Database call returns None
, even though my MongoClient()
call is successful.
#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
I can see that this collection torbot
does exist, so I don't believe that's the issue:
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" }
But I can't find any debug options to see why the call to Database(mc, self.mongodb)
fails.
Upvotes: 1
Views: 401
Reputation: 61235
mongoconn
is a class attribute to access it in the __init__
method you need to prefix it with the class name or self
. In your case you are doing self.mongoconn
will create an instance attribute which is probably not what you want so what you need is MongoConnection.mongoconn = self.__mongo_connect()
. Your __init__
method becomes:
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()
I don't know if what you are doing is something you should be doing though
Upvotes: 1