python - aiohttp:response.status 什么时候可用?

标签 python python-asyncio aiohttp

aiohttp 的入门文档提供了以下客户端示例:

async with aiohttp.ClientSession() as session:
    async with session.get('https://api.github.com/events') as resp:
        print(resp.status)
        print(await resp.text())

我无法理解 response.status 何时可用。我的理解是协程在 await response.read() 行释放控制。在等待回复回复之前,我怎么可能访问状态?

最佳答案

重要区别:await ... 可能会释放对上下文的控制,例如,如果等待的数据不够快。 async with ... 语句也是如此。因此,在响应可用之前,您的代码不会到达 print(resp.status) 行。

例如代码:

import aiohttp
import asyncio
import urllib.parse
import datetime

async def get(session, url):
    print("[{:%M:%S.%f}] getting {} ...".format(datetime.datetime.now(), urllib.parse.urlsplit(url).hostname))
    async with session.get(url) as resp:
        print("[{:%M:%S.%f}] {}, status: {}".format(datetime.datetime.now(), urllib.parse.urlsplit(url).hostname, resp.status))
        doc = await resp.text()
        print("[{:%M:%S.%f}] {}, len: {}".format(datetime.datetime.now(), urllib.parse.urlsplit(url).hostname, len(doc)))

async def main():
    session = aiohttp.ClientSession()

    url = "http://demo.borland.com/Testsite/stadyn_largepagewithimages.html"
    f1 = asyncio.ensure_future(get(session, url))
    print("[{:%M:%S.%f}] added {} to event loop".format(datetime.datetime.now(), urllib.parse.urlsplit(url).hostname))

    url = "https://stackoverflow.com/questions/46445019/aiohttp-when-is-the-response-status-available"
    f2 = asyncio.ensure_future(get(session, url))
    print("[{:%M:%S.%f}] added {} to event loop".format(datetime.datetime.now(), urllib.parse.urlsplit(url).hostname))

    url = "https://api.github.com/events"
    f3 = asyncio.ensure_future(get(session, url))
    print("[{:%M:%S.%f}] added {} to event loop".format(datetime.datetime.now(), urllib.parse.urlsplit(url).hostname))

    await f1
    await f2
    await f3

    session.close()

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

可以产生这样的结果:

[16:42.415481] added demo.borland.com to event loop
[16:42.415481] added stackoverflow.com to event loop
[16:42.415481] added api.github.com to event loop
[16:42.415481] getting demo.borland.com ...
[16:42.422481] getting stackoverflow.com ...
[16:42.682496] getting api.github.com ...
[16:43.002515] demo.borland.com, status: 200
[16:43.510544] stackoverflow.com, status: 200
[16:43.759558] stackoverflow.com, len: 110650
[16:43.883565] demo.borland.com, len: 239012
[16:44.089577] api.github.com, status: 200
[16:44.318590] api.github.com, len: 43055

澄清(thx @deceze):在这里您可以看到(查看括号之间的时间)所有协程在发送检索网站的请求后释放控制,并在等待响应文本时第二次释放控制。此外,与 stackoverflow 相比,borland 的文本太多(不包括其他网络特征),以至于它仅在打印来自 stackoverflow 的文本后才准备好显示,尽管之前已请求。

关于python - aiohttp:response.status 什么时候可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46445019/

相关文章:

python - 在 Jupyter Notebook 中使用 BeautifulSoup 抓取表

python - 如何在 Python 脚本中提供输入答案

python - 取消任务后请解释 "Task was destroyed but it is pending!"

python - aiohttp:如何将sub_app添加到sub_app?

python asyncio 在 key 可用时通过 key 从字典中异步获取数据

python - 将 python 对象转换为 XML 表示

python - 操作列表项 python

python - Python 中使用 asyncio 的多个 websocket 流

python - 当方法基本完成时,AsyncIO 任务不会结束

python异步发布请求