Python async/await 的协程 怎么取到返回值呢?

2021-01-25 17:40:59 +08:00
 PPTX
async def SendHttpReq(url, method, params=None, data=None,
                headers=None,verify=None, cert=None, json_data=None):

    async with httpx.AsyncClient() as client:
        if (method == "GET"):
            response = await client.get(url)
    return response

比如我外部函数想调用这个 SendHttpReq,取到 response 。这个不能直接像函数一样 resp = SendHttpReq()。

1912 次点击
所在节点    Python
5 条回复
Vegetable
2021-01-25 17:42:46 +08:00
外部也需要 resp =await SendHttpReq()
towry
2021-01-25 17:45:37 +08:00
```py
import asyncio

resp = asyncio.ensure_future(SendHttpReq('url', 'GET'))
```
sss495088732
2021-01-26 09:43:09 +08:00
0.0 题外话,httpx,aiohttp 这种异步 http 库都会有套接字溢出的问题.
请见 requests 文档介绍:
Requests 唯一的一个非转基因的 Python HTTP 库,人类可以安全享用。

警告:非专业使用其他 HTTP 库会导致危险的副作用,包括:安全缺陷症、冗余代码症、重新发明轮子症、啃文档症、抑郁、头疼、甚至死亡。
julyclyde
2021-01-26 10:42:29 +08:00
上面 await 和 ensure_future 的区别在哪方面呢
frostming
2021-01-27 09:38:26 +08:00
@julyclyde ensure_future 并不能拿到结果,还是得 await 一下,所以按 1 楼的直接 await 就好

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/748234

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX