'创建mongoengine连接包装器以在多个模块中使用'

2024-05-17 04:03:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个包装器来解决我与mongoengine的所有连接,所以我创建了一个函数,从一个文件读取mongoDB配置并连接到它

函数如下所示:

def connect_mongo_odm(config_file_location, db_name):
    if db_name:
        base_path = ['databases', db_name]
        conf_specs = {
            'host': {
                'path': base_path + ['host']
            },
            'port': {
                'path': base_path + ['port']
        }
    }

    fileConfiguration = dao_utils.readConfiguration(config_file_location, conf_specs)

    auth = None
    host = fileConfiguration.get('host', None)

    host = "mongodb://" + host

    connect(alias=db_name,
            host=host,
            socketKeepAlive=True, socketTimeoutMS=30000)

我用它来表示:

# import previous function
# This is another module in my application
connect_mongo_odm('/path/to/config/file', 'dbName')

但是当我试图保存一个文档时,我得到一个异常,说我没有定义默认连接


Tags: path函数nameconfighostdbbaseport