aiphttp库使用教程
时间: 2023-06-11 19:07:44 浏览: 49
aiohttp是Python 3的异步HTTP客户端/服务器框架。它可以用于编写高性能的异步网络应用程序。下面是使用aiohttp库的一些基本示例:
1. 安装aiohttp库:
```python
pip install aiohttp
```
2. 发送HTTP GET请求:
```python
import aiohttp
import asyncio
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
async with aiohttp.ClientSession() as session:
html = await fetch(session, 'http://example.com')
print(html)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
```
3. 发送HTTP POST请求:
```python
import aiohttp
import asyncio
async def post_data(session, url, data):
async with session.post(url, data=data) as response:
return await response.text()
async def main():
async with aiohttp.ClientSession() as session:
data = {'key': 'value'}
response = await post_data(session, 'http://example.com', data)
print(response)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
```
4. 发送HTTP请求并设置请求头:
```python
import aiohttp
import asyncio
async def fetch(session, url, headers):
async with session.get(url, headers=headers) as response:
return await response.text()
async def main():
async with aiohttp.ClientSession() as session:
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'}
html = await fetch(session, 'http://example.com', headers)
print(html)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
```
以上是aiohttp库的基本用法示例,希望能帮助到你。