Python 未在mongoengine中创建到新dbname的连接
使用PythonMongoEngine,我试图创建数据库并向不同的数据库添加文档。以下是我如何努力做到这一点:Python 未在mongoengine中创建到新dbname的连接,python,pymongo,mongoengine,Python,Pymongo,Mongoengine,使用PythonMongoEngine,我试图创建数据库并向不同的数据库添加文档。以下是我如何努力做到这一点: from mongoengine import * class MongoDataAccessObject(): # method to connect to the database and initialize the tables etc. def __init__(self, my_env, helperObj): print "initial
from mongoengine import *
class MongoDataAccessObject():
# method to connect to the database and initialize the tables etc.
def __init__(self, my_env, helperObj):
print "initializing db for the environment ", my_env
self.con = None
self.dbName = my_env
self.helper_obj = helperObj
try:
self.con = connect(db=self.dbName)
except Exception as e:
print e
def addRecord(self, document_object):
document_object.save()
现在,在创建上述类的对象时,我传递了要创建的不同数据库的名称,并添加如下文档:
for my_env in list_of_envs:
dao = MongoDataAccessObject(my_env, helper_object)
dao.addRecord(myDocument)
现在这里有两个问题:
from mongoengine import *
import datetime
class Page(Document):
title = StringField(max_length=200, required=True)
date_modified = DateTimeField(default=datetime.datetime.now)
def switch(model, db):
model._meta['db_alias'] = db
# must set _collection to none so it is re-evaluated
model._collection = None
return model
register_connection('default', name='testing')
register_connection('mycon', name='db1')
page = Page(title="Test Page")
page = switch(page, 'mycon')
page.save()
这将工作并创建一个名为db1的数据库,并将文档存储在其中
现在我再次这样做:
register_connection('mycon2', name='db2')
page = Page(title="Test Page")
page = switch(page, 'mycon2')
page.save()
与我的预期相反,这次没有创建db2(从mongo客户端和Robomongo客户端都进行了检查),但是文档保存成功了
因此,为了找出答案,我们重复了上述练习,并做了如下小改动:
register_connection('mycon2', name='db2')
page = Page(title="Test Page")
page = switch(page, 'mycon2')
x = page.save()
# did a dir(x) and found that there is _get_db, so tried it out as below
x._get_db()
结果是:
数据库(MongoClient(主机=['localhost:27017'],文档类=dict,tz\u-aware=False,connect=True,read\u-preference=Primary(),u'db2'))
我猜这意味着文档被保存在一个名为db2的数据库中。但这个db2到底在哪里呢???为什么我不能通过mongo客户端甚至Robomongo等来查看它?最后,我能找到的实现上述目标的唯一方法是通过上下文管理器和MongoEngine提供的语句,MongoEngine也有很好的文档记录关于: 在上面的代码中,我是这样做的:
for my_env in list_of_envs:
dao = MongoDataAccessObject(my_env, helper_object)
dao.addRecord(myDocument)
在对db的第一次调用中,需要创建一个默认db,该db应将别名作为默认值。只有这样才能创建另一个别名,否则Mongoengine会抛出一个错误,表示找不到默认db
为此,当创建第一个db对象时,会向MongoDataAccessObject的_init__发送一个False标志
为此,MongoDataAccessObject也被更改为如下内容:
class MongoDataAccessObject():
# method to connect to the database and initialize the tables etc.
def __init__(self, my_env, helperObj, is_default_db_set):
print "initializing db for the environment ", my_env
self.con = None
self.dbName = my_env
self.helper_obj = helperObj
self.db_alias = my_env
self.is_default_db_set = is_default_db_set
try:
# all of this part with the is_default_db_set and register_connection() is needed because MongoEngine does not
# provide a simple way of changing dbs or switching db connections. The only way to do it is through the switch_db()
# context manager they provide (which has been used in the addRecord() below)
if not self.is_default_db_set:
self.con = connect(db=self.dbName, alias='default')
else:
# register_connection(alias_name, db_name)
register_connection(self.db_alias, self.dbName)
except Exception as e:
print e
addRecord()也被修改为:
def addRecord(self, document_object):
with switch_db(model_object, self.db_alias) as model_object:
document_object = model_object()
document_object.save()
以上这部分:
for my_env in list_of_envs:
dao = MongoDataAccessObject(my_env, helper_object)
dao.addRecord(myDocument)
也修改为:
for my_env in list_of_envs:
dao = MongoDataAccessObject(my_env,helper_object,mongo_default_db_flag)
dao.addRecord(myDocument)
这似乎对我很有帮助