python并发请求接口
时间: 2023-11-02 19:57:21 浏览: 42
在Python中实现并发请求接口的方式有很多种,下面介绍其中两种比较常见的方式。
1. 使用requests和grequests库
requests是Python中常用的HTTP库,而grequests是requests库的异步版本,可以实现并发请求。
示例代码:
```python
import requests
import grequests
urls = [
'https://www.baidu.com',
'https://www.google.com',
'https://www.bing.com'
]
# 顺序请求
for url in urls:
response = requests.get(url)
print(response.content)
# 并发请求
rs = (grequests.get(url) for url in urls)
responses = grequests.map(rs)
for response in responses:
print(response.content)
```
2. 使用asyncio和aiohttp库
asyncio是Python中内置的协程库,而aiohttp是基于asyncio的HTTP库,可以实现异步请求。
示例代码:
```python
import asyncio
import aiohttp
urls = [
'https://www.baidu.com',
'https://www.google.com',
'https://www.bing.com'
]
async def fetch(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.text()
# 顺序请求
for url in urls:
content = asyncio.run(fetch(url))
print(content)
# 并发请求
tasks = [asyncio.create_task(fetch(url)) for url in urls]
contents = asyncio.run(asyncio.gather(*tasks))
for content in contents:
print(content)
```
以上两种方法都可以实现并发请求接口,具体使用哪种方式可以根据实际情况进行选择。