V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
PPTX
V2EX  ›  Python

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

  •  
  •   PPTX · 2021-01-25 17:40:59 +08:00 · 1894 次点击
    这是一个创建于 1180 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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()。

    5 条回复    2021-01-27 09:38:26 +08:00
    Vegetable
        1
    Vegetable  
       2021-01-25 17:42:46 +08:00
    外部也需要 resp =await SendHttpReq()
    towry
        2
    towry  
       2021-01-25 17:45:37 +08:00
    ```py
    import asyncio

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

    警告:非专业使用其他 HTTP 库会导致危险的副作用,包括:安全缺陷症、冗余代码症、重新发明轮子症、啃文档症、抑郁、头疼、甚至死亡。
    julyclyde
        4
    julyclyde  
       2021-01-26 10:42:29 +08:00
    上面 await 和 ensure_future 的区别在哪方面呢
    frostming
        5
    frostming  
       2021-01-27 09:38:26 +08:00
    @julyclyde ensure_future 并不能拿到结果,还是得 await 一下,所以按 1 楼的直接 await 就好
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1544 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 17:00 · PVG 01:00 · LAX 10:00 · JFK 13:00
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.