$ ls ~yifei/notes/

Python 异步 http 请求库 —— aiohttp

Posted on:

Last modified:

aiohttp 是 Python 异步编程生态中出现比较早的一个 http 请求库,依托于 asyncio, 性能非常吓人。 下面列举几个常见的用法:

import aiohttp
import asyncio

async def fetch(session, url):
    async with session.get(url) as response:
        return await response.text()

async def main():
    urls = [
            "http://python.org",
            "https://google.com",
            "http://yifei.me"
        ]
    tasks = []
    async with aiohttp.ClientSession() as session:
        for url in urls:
            tasks.append(fetch(session, url))
        htmls = await asyncio.gather(*tasks)
        for html in htmls:
            print(html[:100])

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
WeChat Qr Code

© 2016-2022 Yifei Kong. Powered by ynotes

All contents are under the CC-BY-NC-SA license, if not otherwise specified.

Opinions expressed here are solely my own and do not express the views or opinions of my employer.

友情链接: MySQL 教程站