推荐学习书目
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 · Jan 25, 2021 · 2857 views
    This topic created in 1949 days ago, the information mentioned may be changed or developed.
    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 replies    2021-01-27 09:38:26 +08:00
    Vegetable
        1
    Vegetable  
       Jan 25, 2021
    外部也需要 resp =await SendHttpReq()
    towry
        2
    towry  
       Jan 25, 2021
    ```py
    import asyncio

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

    警告:非专业使用其他 HTTP 库会导致危险的副作用,包括:安全缺陷症、冗余代码症、重新发明轮子症、啃文档症、抑郁、头疼、甚至死亡。
    julyclyde
        4
    julyclyde  
       Jan 26, 2021
    上面 await 和 ensure_future 的区别在哪方面呢
    frostming
        5
    frostming  
       Jan 27, 2021
    @julyclyde ensure_future 并不能拿到结果,还是得 await 一下,所以按 1 楼的直接 await 就好
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1099 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 466ea39e · 42ms · UTC 22:56 · PVG 06:56 · LAX 15:56 · JFK 18:56
    ♥ Do have faith in what you're doing.