一、aiohttp的使用
1、安装与使用
pip install aiohttp
2、简单实例使用
aiohttp的自我介绍中就包含了客户端和服务器端,所以我们分别来看下客户端和服务器端的简单实例代码。
- 客户端:
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://httpbin.org/headers")
print(html)
asyncio.run(main())
"""输出结果:
{
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Host": "httpbin.org",
"User-Agent": "Python/3.7 aiohttp/3.6.2"
}
}
"""
这个代码是不是很简单,一个函数用来发起请求,另外一个函数用来下载网页。
3、入门
- 简单示范
首先是学习客户端,也就是用来发送http请求的用法。首先看一段代码,会在代码中讲述需要注意的地方:
import aiohttp
import asyncio
async def main():
async with aiohttp.ClientSession() as session:
async with session.get('http://httpbin.org/get') as resp:
print(resp.status)
print(await resp.text())
asyncio.run(main())
- 代码解释:
在网络请求中,一个请求就是一个会话,然后aiohttp使用的是ClientSession来管理会话,所以第一个重点,看一下ClientSession:
class ClientSession:
"""First-class interface for making HTTP requests."""
在源码中,这个类的注释是使用HTTP请求接口的第一个类。然后上面的代码就是实例化一个ClientSession类然后命名为session,然后用session去发送请求。这里有一个坑,那就是ClientSession.get()协程的必需参数只能是str类和yarl.URL的实例。
当然这只是get请求,其他的请求都是支持的:
session.post('http://httpbin.org/post', data='data')
session.get('http://httpbin.org/get')
4、在URL中传递参数
有时候在发起网络请求的时候需要附加一些参数到url中,这一点也是支持的。
import aiohttp
import asyncio
async def main():
async with aiohttp.ClientSession() as session:
params = {
'key1': 'value1', 'key2': 'value2'}
async with session.get('http://httpbin.org/get',
params=params) as resp:
print(resp

最低0.47元/天 解锁文章
160

被折叠的 条评论
为什么被折叠?



