python 通过 asyncio 异步操作 mongo, 可在 jupyter 上运行

导包

import asyncio
import motor.motor_asyncio
import nest_asyncio  # jupyter 上运行需要
nest_asyncio.apply()  # jupyter 上运行需要

创建类,可直接复制使用,可添加相应的方法或者修改

实现了,查询、插入,断开连接,的方法。

查询:可做条件查询,返回的是 [{documentation}, {documentation}, ...]
插入:传入可为 {documentation} ,或者:[{documentation}, {documentation}, ...]

"""operation mongodb"""
class Mongo(object):

    __instance = None
    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = object.__new__(cls)
        return cls.__instance

    def __init__(self, host, port, db, user='', pwd=''):

        if user:
            self.client = motor.motor_asyncio.AsyncIOMotorClient(host, port)
            motor.motor_asyncio.AsyncIOMotorClient(f'mongodb://{user}:{pwd}@localhost:27017')
            self.db = self.client[db]
        else:
            # no user, no password
            self.client = motor.motor_asyncio.AsyncIOMotorClient(host, port)
            self.db = self.client[db]

    def insert(self, coll, data):
        """
        insert data
        :param coll:
        :param data: Dict or List(Dict, Dict, )
        :return:
        """
        loop = asyncio.get_event_loop()
        loop.run_until_complete(self.__insert(coll, data))

    async def __insert(self, coll, data):
        c = self.db[coll]

        if isinstance(data, dict):
            res = await c.insert_one(data)
            print(f'inserted {len(res.inserted_ids)} docs in {coll}')
        elif isinstance(data, list):
            res = await c.insert_many(data)
            print(f'inserted {len(res.inserted_ids)} docs in {coll}')

        else:
            print(f"data type only is List or Dict,no {type(data)}")

    def find(self, coll, *args, **kwargs):
        loop = asyncio.get_event_loop()
        return loop.run_until_complete(self.__find(coll, *args, **kwargs))

    async def __find(self, coll, *args, **kwargs):
        c = self.db[coll]
        cursor = c.find(*args, **kwargs)
        return [dic async for dic in cursor]

    def close(self):
        self.client.close()

使用

mongo = Mongo(host=host, port=port, db='库名')  # 有密码的,可u添加: user='', pwd=''
# {"type" : "train"} 条件查询,可不要
# {"type": 1}, 指定返回字段,可不要
train = mongo.find("表名", {"type" : "train"}, {"type": 1}) # 返回[{documentation}, {documentation}, ...]

mongo.insert("表名", data)  # data  `{documentation}`  ,或者:`[{documentation}, {documentation}, ...]`
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Python异步读取Mongo的方法有多种,这里介绍一种使用AsyncIO和Motor库的方式: 首先需要安装Motor库,可以使用pip命令进行安装: ``` pip install motor ``` 接下来可以使用以下代码来异步读取Mongo中的数据: ``` import asyncio import motor.motor_asyncio async def main(): # 创建Motor客户端 client = motor.motor_asyncio.AsyncIOMotorClient('mongodb://localhost:27017') # 选择数据库和集合 db = client.test_database collection = db.test_collection # 查询数据 async for document in collection.find(): print(document) # 运行异步事件循环 if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(main()) ``` 上述代码中,我们首先使用AsyncIOMotorClient创建了一个异步Mongo客户端,然后选择了要查询的数据库和集合。在主函数中,使用async for循环异步查询Mongo中的数据,并打印出来。 需要注意的是,在使用异步Mongo客户端时,查询操作需要使用异步的for循环(async for),而不能使用普通的for循环。 ### 回答2: 在Python异步读取MongoDB可以使用异步IO的库来实现,比如使用`asyncio`库结合`Motor`库。 首先,我们需要安装`Motor`库,可以使用以下命令来安装: ``` pip install motor ``` 然后,我们可以使用以下代码来演示异步读取MongoDB的例子: ```python import asyncio import motor.motor_asyncio async def read_from_mongo(): client = motor.motor_asyncio.AsyncIOMotorClient('localhost', 27017) db = client['testdb'] collection = db['testcollection'] cursor = collection.find() async for document in cursor: print(document) client.close() asyncio.run(read_from_mongo()) ``` 在上面的例子中,我们首先创建了一个`motor.motor_asyncio.AsyncIOMotorClient`对象来连接MongoDB数据库。然后,我们选择了要读取的数据库和集合。 接着,我们使用`collection.find()`方法来查询所有的文档,并通过`async for`循环遍历结果集。在循环中,我们可以对每个文档执行自己的操作。 最后,我们需要关闭客户端连接。 需要注意的是,在上面的代码中,我们使用了`asyncio.run()`来运行异步函数。这是Python 3.7及以上版本的标准库中提供的运行异步函数的方法。 通过使用`Motor`库和`asyncio`库,我们可以很方便地在Python中实现异步读取MongoDB操作。 ### 回答3: 在Python异步读取Mongo是通过使用异步驱动程序来实现的,最常用的异步驱动程序是`motor`。下面是使用`motor`异步读取Mongo的一般步骤: 首先,安装`motor`驱动程序。可以使用`pip`命令进行安装: ``` pip install motor ``` 接下来,导入`motor`库并创建一个异步客户端来连接Mongo数据库: ```python import motor.motor_asyncio client = motor.motor_asyncio.AsyncIOMotorClient('mongodb://localhost:27017') ``` 然后,选择要读取的数据库和集合: ```python db = client['mydatabase'] collection = db['mycollection'] ``` 接下来,使用`find`方法来查询文档。由于是异步操作,可以使用`await`关键字来等待查询结果: ```python async def read_data(): cursor = collection.find() async for document in cursor: print(document) ``` 在这个例子中,使用了一个异步的`for`循环来遍历查询结果,并打印每个文档。 最后,使用`asyncio`库来运行异步函数: ```python import asyncio asyncio.run(read_data()) ``` 这样就可以异步读取Mongo数据库。需要注意的是,在使用异步读取Mongo时,应该避免在运行期间进行阻塞的操作,以充分利用异步的优势。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值