Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将aio pika与FastAPI结合使用?_Python_Asynchronous_Fastapi - Fatal编程技术网

Python 如何将aio pika与FastAPI结合使用?

Python 如何将aio pika与FastAPI结合使用?,python,asynchronous,fastapi,Python,Asynchronous,Fastapi,我想在异步工作时使用FastAPI和aio pika创建一个REST服务。对于其他异步数据库驱动程序,我可以在启动时在路由处理程序中获取客户端时创建它们。例如,对于motor,我将声明简单连接管理器: from motor.motor_asyncio import AsyncIOMotorClient class Database: client: AsyncIOMotorClient = None db = Database() async def connect_to_m

我想在异步工作时使用FastAPI和aio pika创建一个REST服务。对于其他异步数据库驱动程序,我可以在启动时在路由处理程序中获取客户端时创建它们。例如,对于motor,我将声明简单连接管理器:

from motor.motor_asyncio import AsyncIOMotorClient


class Database:
    client: AsyncIOMotorClient = None


db = Database()


async def connect_to_mongo():
    db.client = AsyncIOMotorClient("mongo:27017")


async def close_mongo_connection():
    db.client.close()


async def get_mongo_client() -> AsyncIOMotorClient:
    return db.client
然后添加两个处理程序:

app.add_event_handler("startup", connect_to_mongo)
app.add_event_handler("shutdown", close_mongo_connection)
然后只需使用
get\u mongo\u client
就可以为我的处理程序获取一个

这里的问题是,
aio-pika
需要
asyncio
循环才能运行。以下是文档中的一个示例:

connection = await aio_pika.connect_robust(
        "amqp://guest:guest@127.0.0.1/", loop=loop
    )
使用FastAPI,我没有异步IO循环。是否有任何方法可以将其与示例中的接口一起使用?我是否可以使用
asyncio.get\u event\u loop()
创建新循环,并将其传递给
connect\u robust
,而不在任何地方使用它?像这样:

connection = await aio_pika.connect_robust(
            "amqp://guest:guest@127.0.0.1/", loop=asyncio.get_event_loop()
        )
好的,那么,根据,我可以使用
connect
而不是
connect\u-robust

connection = await aio_pika.connect(
        "amqp://guest:guest@127.0.0.1/"
    )