aiohttp
3.11.10
要从网络获取某些内容:
import aiohttp
import asyncio
async def main ():
async with aiohttp . ClientSession () as session :
async with session . get ( 'http://python.org' ) as response :
print ( "Status:" , response . status )
print ( "Content-type:" , response . headers [ 'content-type' ])
html = await response . text ()
print ( "Body:" , html [: 15 ], "..." )
asyncio . run ( main ())
这打印:
状态:200 内容类型:text/html;字符集=utf-8 正文: <!doctype html> ...
来自请求?了解为什么我们需要这么多行。
使用简单服务器的示例:
# examples/server_simple.py
from aiohttp import web
async def handle ( request ):
name = request . match_info . get ( 'name' , "Anonymous" )
text = "Hello, " + name
return web . Response ( text = text )
async def wshandle ( request ):
ws = web . WebSocketResponse ()
await ws . prepare ( request )
async for msg in ws :
if msg . type == web . WSMsgType . text :
await ws . send_str ( "Hello, {}" . format ( msg . data ))
elif msg . type == web . WSMsgType . binary :
await ws . send_bytes ( msg . data )
elif msg . type == web . WSMsgType . close :
break
return ws
app = web . Application ()
app . add_routes ([ web . get ( '/' , handle ),
web . get ( '/echo' , wshandle ),
web . get ( '/{name}' , handle )])
if __name__ == '__main__' :
web . run_app ( app )
https://aiohttp.readthedocs.io/
https://github.com/aio-libs/aiohttp-demos
请随意提出请求以将链接添加到这些页面!
aio-libs 讨论:https://github.com/aio-libs/aiohttp/discussions
矩阵:#aio-libs:matrix.org
我们支持堆栈溢出。请在您的问题中添加aiohttp标签。
您也可以选择安装 aiodns 库(为了速度,强烈推荐)。
aiohttp
在 Apache 2 许可证下提供。
aiohttp 社区感谢 Keepsafe (https://www.getkeepsafe.com) 在项目早期的支持。
最新的开发人员版本可在 GitHub 存储库中找到:https://github.com/aio-libs/aiohttp
如果您对效率感兴趣,AsyncIO 社区在官方 wiki 上维护了一个基准列表:https://github.com/python/asyncio/wiki/Benchmarks