MST

星途 面试题库

面试题:网络编程之Python并发编程中等难度题

在Python的网络编程中,使用`asyncio`库实现一个简单的并发HTTP请求程序,要求能够同时发起多个请求并处理响应。请简述实现思路并给出核心代码。
33.2万 热度难度
后端开发网络编程

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 导入必要的库:导入asyncio用于异步操作,aiohttp用于进行异步HTTP请求。
  2. 定义一个函数:该函数负责发起单个HTTP请求并处理响应。
  3. 创建任务列表:将多个请求任务添加到任务列表中。
  4. 运行事件循环:使用asyncio的事件循环来并发执行这些任务。

核心代码

import asyncio
import aiohttp


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


async def main():
    urls = [
        'http://example.com',
        'http://example.org',
        'http://example.net'
    ]
    async with aiohttp.ClientSession() as session:
        tasks = [fetch(session, url) for url in urls]
        results = await asyncio.gather(*tasks)
        for result in results:
            print(result)


if __name__ == "__main__":
    asyncio.run(main())