前言
本文翻译自aiohttp官方文档,如有纰漏,欢迎指出。
aiohttp是一个为python提供异步http 客户端/服务端编程,基于asyncio(python用于支持异步编程的标准库)的异步库。
核心功能:
同时支持客户端使用和服务端使用。
同时支持服务端websockets组件和客户端websockets组件,开箱即用呦。
web服务器具有中间件,信号组件和可插拔路由的功能。
aiohttp库安装:
pip install aiohttp
你可能还想安装更快的cchardet库来代替chardet进行解码:
pip install cchardet
对于更快的客户端api dns解析方案,aiodns是个很好的选择,极力推荐:
pip install aiodns
快速开始:
客户端例子:
import aiohttp
import asyncio
import async_timeout
async def fetch(session, url):
with async_timeout.timeout(10):
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)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
服务端例子:
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.router.add_get('/', handle)
app.router.add_get('/{name}', handle)
web.run_app(app)
注意:
这篇文档的所有例子都是利用 async/await 语法来完成的,此语法介绍请看pep 492,此语法仅python 3.5+有效。 如果你使用的是python 3.4, 请将await替换成yield from,将async 替换成带有 @corotine装饰器的def. 比如
async def coro(...):
ret = await f()
应替换为:
@asyncio.coroutine
def coro(...):
ret = yield from f()
如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!