在Python Quart中获取同步代码的结果

问题描述

我在Quart中有一条异步路由,必须在其中运行一个同步代码块。根据文档,我应该使用quart.utils中的run_sync来确保同步函数不会阻塞事件循环。

def sync_processor():
    request = requests.get('https://api.github.com/events')
    return request

@app.route('/')
async def test():
    result = run_sync(sync_processor)
    print(result)
    return "test"

但是,打印(结果)返回。如何获取请求对象而不是

解决方法

您丢失了await,因为run_sync用一个协程函数包装了该函数,然后您需要调用该协程函数,即result = await run_sync(sync_processor)()或完整函数,

def sync_processor():
    request = requests.get('https://api.github.com/events')
    return request

@app.route('/')
async def test():
    result = await run_sync(sync_processor)()
    print(result)
    return "test"