迁移到PyMongo Async
重要
Overview
The PyMongo Async driver is a unification of PyMongo and the Motor library. In this guide, you can identify the changes you must make to migrate an application from PyMongo or Motor to the PyMongo Async driver.
从Motor迁移
PyMongo异步驾驶员的功能与Motor库类似,但由于直接使用Python Asyncio 而不是将工作委托给线程池,因此可以改善延迟和吞吐量。 在大多数情况下,您可以使用 AsyncMongoClient
代替 MotorClient
并将应用程序的导入语句更改为从 pymongo
导入,从而将现有Motor应用程序直接迁移到PyMongo Async。
以下示例显示了在Motor中与PyMongo Async 中使用客户端进行写入操作的导入差异:
# Motor client import from motor.motor_asyncio import AsyncIOMotorClient # PyMongo Async client import from pymongo import AsyncMongoClient
To see a list of the asynchronous methods available in the PyMongo Async driver, see the 异步方法 section in the PyMongo to PyMongo Async guide.
以下部分介绍了从Motor迁移到PyMongo异步驾驶员程序时必须在应用程序中实现的方法签名更改。
方法签名更改
以下Motor方法签名在PyMongo异步驾驶员中的行为有所不同:
AsyncMongoClient.__init__()
不接受io_loop
参数。PyMongo异步驾驶员中不存在
AsyncCursor.each()
。PyMongo异步驾驶员中不存在
MotorGridOut.stream_to_handler()
。AsyncCursor.to_list(0)
在PyMongo异步驾驶员中无效。请改用to_list(None)
。MongoClient
具有线程安全性,可供多个线程使用,但AsyncMongoClient
并非线程安全的,只能由单个事件循环使用。
Migrate from PyMongo
The PyMongo Async driver behaves similarly to PyMongo, but all methods that perform network operations are coroutines and must be awaited. To migrate from PyMongo to PyMongo Async, you must update your code in the following ways:
将所有使用的
MongoClient
替换为AsyncMongoClient
。为所有异步方法调用添加
await
关键字。如果在函数内部调用异步方法,请将该函数标记为
async
。
以下部分介绍如何实现异步API。
异步方法
下表列出了PyMongo异步驾驶员中可用的异步方法。 要调用这些方法,您必须对其进行 await
操作并在 async
函数内进行调用。
客户端方法
方法 | 例子 | |||
---|---|---|---|---|
|
| |||
|
| |||
|
| |||
|
| |||
|
| |||
|
|
数据库方法
方法 | 例子 | ||
---|---|---|---|
|
| ||
|
| ||
|
| ||
|
| ||
|
| ||
|
| ||
|
| ||
|
| ||
|
| ||
|
|
集合方法
方法 | 例子 | ||
---|---|---|---|
|
| ||
|
| ||
|
| ||
|
| ||
|
| ||
|
| ||
|
| ||
|
| ||
|
| ||
|
| ||
|
| ||
|
| ||
|
| ||
|
| ||
|
| ||
|
| ||
|
| ||
|
| ||
|
| ||
|
| ||
|
| ||
|
| ||
|
| ||
|
| ||
|
| ||
|
| ||
|
| ||
|
| ||
|
| ||
|
| ||
|
|