首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python asyncio REST api调用出错

问python asyncio REST api调用出错
EN

Stack Overflow用户
提问于 2018-08-03 22:26:49
回答 3查看 856关注 0票数 2

我试图使用asyncio调用一个REST API async,但我一直收到错误"coroutine was never awaited“,这是我理解的。但是我想要这样的行为,我希望我的函数只通过发布而不是等待结果来结束。以下是我的代码

代码语言:javascript
复制
async def callCoroutine:
    #call a REST API 

def lambda_handler(event, context):   
    loop = asyncio.get_event_loop()
    task = loop.create_task(callCoroutine(data))
    return

有人能帮帮忙吗?

EN

Stack Overflow用户

发布于 2018-08-22 17:01:59

在您的示例中,主线程正在同步运行。因此,您需要使用asyncio.run_coroutine_threadsafe在另一个线程中运行异步循环。

代码语言:javascript
复制
import asyncio
import threading

# Run asyncio loop in other thread
loop = asyncio.new_event_loop()
threading.Thread(target=loop.run_forever).start()


async def call_coroutine(data):
    # call a REST API 
    return


def lambda_handler(event, context):   
    # Run the coroutine on the loop of other thread
    future = asyncio.run_coroutine_threadsafe(call_coroutine(data), loop)
    # If need to get result: 
    result = future.result()  # This will block the main thread

    do_something_else()
    return

# If need to stop the asyncio loop
loop.call_soon_threadsafe(loop.stop)
票数 1
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51674786

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档