Python开发【模块】:aiohttp(二)

时间:2022-12-20 23:05:05

AIOHTTP

1、文件上传

① 单个文件上传

服务端

 async def post(self, request):
reader = await request.multipart()
# /!\ 不要忘了这步。(至于为什么请搜索 Python 生成器/异步)/!\
file = await reader.next()
filename = file.filename
# 如果是分块传输的,别用Content-Length做判断。
size = 0
with open(filename, 'wb') as f:
while True:
chunk = await file.read_chunk() # 默认是8192个字节。
if not chunk:
break
size += len(chunk)
f.write(chunk) return web.Response(text='{} sized of {} successfully stored'
''.format(filename, size))

客户端

import aiohttp
import asyncio url = 'http://127.0.0.1:8080/'
files = {'file': open('files/1M.wav', 'rb'),} async def fetch(session, url):
async with session.post(url,data=files) as response:
return await response.text() async def main():
async with aiohttp.ClientSession() as session:
html = await fetch(session, 'http://127.0.0.1:8080')
print(html) loop = asyncio.get_event_loop()
loop.run_until_complete(main())

 ② 传输多个文件及其他参数

服务端

    async def post(self, request):
reader = await request.multipart()
data = {}
async for read in reader:
filename = read.filename
if filename is not None:
size = 0
with open('./' + filename, 'wb') as f:
while True:
chunk = await read.read_chunk() # 默认是8192个字节。
if not chunk:
break
size += len(chunk)
f.write(chunk)
else:
value = await read.next()
key = read.name
data[key] = str(value, encoding='utf-8')
print(data)
return web.Response()

客户端

import aiohttp
import asyncio url = 'http://127.0.0.1:8080/'
files = {'file': open('files/1M.wav', 'rb'),
'file2': open('files/0.5M.wav', 'rb'),
'name':'000001',
} async def fetch(session, url):
async with session.post(url,data=files) as response:
return await response.text() async def main():
async with aiohttp.ClientSession() as session:
html = await fetch(session, 'http://127.0.0.1:8080')
print(html) loop = asyncio.get_event_loop()
loop.run_until_complete(main())