首页 > 解决方案 > 在 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"

但是 print(result) 返回 <function sync_processor at 0x742d18a0>。如何获取请求对象而不是 <function sync_processor at 0x742d18a0>。

标签: pythonasynchronousrequestsynchronizationquart

解决方案


您缺少一个awaitasrun_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"

推荐阅读