aiohttp 是一个基于异步的 Python HTTP 客户端/服务器框架,它允许你编写高性能的异步网络应用程序。它建立在 Python 的协程和异步 I/O 模型上,并利用了 Python 3.5+ 中引入的 asyncio 库。官网:https://docs.aiohttp.org
pip install aiohttp
'''网址:https://101.qq.com/#/hero'''import aiohttp
import asyncio
import json
import os
class LOL:
request_url = {
'hero_info': 'https://game.gtimg.cn/images/lol/act/img/js/heroList/hero_list.js?ts=2822604',
'skin': 'https://game.gtimg.cn/images/lol/act/img/skin/big{}00{}.jpg' }
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36' }
def __init__(self):
pass async def get_hero(self):
async with aiohttp.ClientSession() as request:
response = await request.get(self.request_url['hero_info'],headers=self.headers)
hero_json_str = await response.text()
task_list = []
for item in json.loads(hero_json_str)['hero']:
task = asyncio.create_task(self.get_skin(request,item))
task_list.append(task)
await asyncio.wait(task_list)
async def get_skin(self,request,hero_info):
if not os.path.exists(hero_info["name"]):
os.mkdir(hero_info["name"])
for nu in range(30):
response = await request.get(self.request_url['skin'].format(hero_info['heroId'], nu))
if response.status == 200:
skin_info = await response.read()
with open(f'{hero_info["name"]}{os.sep}{nu}.jpg', 'wb') as file:
file.write(skin_info)
print('英雄皮肤已下载')
else:
breakif __name__ == '__main__':
lol = LOL()
asyncio.run(lol.get_hero())
from aiohttp import web
import os
routes = web.RouteTableDef()
@routes.get('/') #访问http://localhost:8009/
def index(request):
response = web.Response(text="Hello, world!")
return response
@routes.route('GET','/test') #访问http://localhost:8009/test
def test(request):
response = web.Response(text="测试")
return response
routes.static('/skin',path=os.path.join(os.getcwd(),'img')) #访问http://localhost:8009/skin/万花通灵/0.jpg
web.static('/skin',path=os.path.join(os.getcwd(),'img')) #访问http://localhost:8009/skin/万花通灵/0.jpg
app = web.Application()
app.add_routes(routes)
web.run_app(app,host='localhost',port=8009)
from aiohttp import web
import os
def index(request):
response = web.Response(text="Hello, world!")
return response
def test(request):
response = web.Response(text="测试")
return response
app = web.Application()
app.router.add_get('/',index)#访问http://localhost:8009/
app.router.add_route('GET','/test',test) #访问http://localhost:8009/test
app.router.add_static('/skin',path=os.path.join(os.getcwd(),'img')) #访问http://localhost:8009/skin/万花通灵/0.jpg
web.static('/skin',path=os.path.join(os.getcwd(),'img')) #访问http://localhost:8009/skin/万花通灵/0.jpg
web.run_app(app,host='localhost',port=8009)
from aiohttp import web
# 定义全局中间件函数
@web.middleware
async def middleware_handler(request, handler):
# 在请求处理之前执行的代码
print('全局请求处理之前执行的代码')
# 调用下一个中间件或请求处理函数
response = await handler(request)
# 在请求处理之后执行的代码
print('全局请求处理之后执行的代码')
return response
# 定义test路由中间件函数
@web.middleware
async def test_handler(request, handler):
# 在请求处理之前执行的代码
print('test路由在请求处理之前执行的代码')
# 调用下一个中间件或请求处理函数
response = await handler(request)
# 在请求处理之后执行的代码
print('test路由在请求处理之后执行的代码')
return response
# 创建应用程序
app = web.Application()
routes = web.RouteTableDef()
@routes.get('/')
async def index(request):
return web.Response(text='首页')
# 定义处理函数
async def test_response(request):
return web.Response(text='测试')
@routes.get('/test')
async def test(request):
response = await test_handler(request,test_response)
return response
# 将中间件添加到应用程序
app.middlewares.append(middleware_handler)
app.add_routes(routes)
web.run_app(app,host='localhost',port=8009)
from aiohttp import web
# WebSocket 处理函数
async def websocket_handler(request):
ws = web.WebSocketResponse() # 创建 WebSocketResponse 对象
await ws.prepare(request) # 准备 WebSocket 连接
async for msg in ws: # 处理 WebSocket 的消息
if msg.type == web.WSMsgType.TEXT:
if msg.data == 'close':
await ws.close()
else:
await ws.send_str('You said: ' + msg.data)
elif msg.type == web.WSMsgType.ERROR:
print('WebSocket connection closed with exception %s' % ws.exception())
return ws
# 创建应用程序
app = web.Application()
# 将 WebSocket 处理函数添加到路由中
app.router.add_get('/ws', websocket_handler)
# 运行应用程序
web.run_app(app)