aiohttp
aiohttp
1. aiohttp
基于asyncio实现的异步HTTP client/server。
但做为一个server,aiohttp太底层了一点,一般多使用它的client端。
文档:https://docs.aiohttp.org/en/stable/
1.1. 安装
pip install aiohttp
2. 使用
2.1. 简单使用
下面是基于aiohttp的server/client。
Client example:
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://python.org')
print(html)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Server example:
from aiohttp import web
async def handle(request):
name = request.match_info.get('name', "Anonymous")
text = "Hello, " + name
return web.Response(text=text)
app = web.Application()
app.add_routes([web.get('/', handle),
web.get('/{name}', handle)])
if __name__ == '__main__':
web.run_app(app)
3. client
import aiohttp
async with aiohttp.ClientSession() as session:
async with session.get('http://httpbin.org/get') as resp:
print(resp.status)
print(await resp.text())
# 其它请求
session.post('http://httpbin.org/post', data=b'data')
session.put('http://httpbin.org/put', data=b'data')
session.delete('http://httpbin.org/delete')
session.head('http://httpbin.org/get')
session.options('http://httpbin.org/get')
session.patch('http://httpbin.org/patch', data=b'data')
# 传参
params = {'key1': 'value1', 'key2': 'value2'}
async with session.get('http://httpbin.org/get',
params=params) as resp:
expect = 'http://httpbin.org/get?key2=value2&key1=value1'
assert str(resp.url) == expect
# response
async with session.get('https://api.github.com/events') as resp:
print(resp.status)
print(await resp.text())
# 输出
# 200
# '[{"created_at":"2015-06-12T14:06:22Z","public":true,"actor":{...
await resp.text(encoding='windows-1251')
# 二进制数据
print(await resp.read())
# JSON Request
async with aiohttp.ClientSession() as session:
async with session.post(url, json={'test': 'object'})
# JSON response
async with session.get('https://api.github.com/events') as resp:
print(await resp.json())
# 流数据
async with session.get('https://api.github.com/events') as resp:
await resp.content.read(10)
# 更进一步使用
with open(filename, 'wb') as fd:
while True:
chunk = await resp.content.read(chunk_size)
if not chunk:
break
fd.write(chunk)
# 请求超时 Timeouts
timeout = aiohttp.ClientTimeout(total=60)
async with aiohttp.ClientSession(timeout=timeout) as session:
...
async with session.get(url, timeout=timeout) as resp:
日拱一卒无有尽,功不唐捐终入海

浙公网安备 33010602011771号