python - 在 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>。
解决方案
您缺少一个await
asrun_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"
推荐阅读
- javascript - 无法在 Javascript 中删除对象属性
- .net - 机器人对话框不等待
- typescript - 在 Ionic 中转换为 HmacSHA256 中的字符串时出现不一致
- database - sqLite - 每个表或整个数据库文件的锁定?
- java - 从 Google Drive 下载文件 - 缺少方法?(爪哇)
- javascript - JavaScript:本地存储“布尔”未打开第一个函数调用
- html - 为什么我的链接说找不到文件?
- matlab - 如何使用 MATLAB 在结构内创建新字段?
- laravel-5 - 使用 laravel 黄昏测试 vuetify v-select
- javascript - 如何获取 j 查询中的下一个元素?