注意例子中的警告。通常Reuest.post()会把所有数据读到内容,可能会引起OOM(out of memory 内存炸了)错误。你可以用Request.multipart()来避免这种情况,它返回的是multipart读取器。
async def store_mp3_handler(request):
reader = await request.multipart()
# /!\ 不要忘了这步。(至于为什么请搜索 Python 生成器/异步)/!\
mp3 = await reader.next()
filename = mp3.filename
# 如果是分块传输的,别用Content-Length做判断。
size = 0
with open(os.path.join('/spool/yarrr-media/mp3/', filename), 'wb') as f:
while True:
chunk = await mp3.read_chunk() # 默认是8192个字节。
if not chunk:
break
size += len(chunk)
f.write(chunk)
return web.Response(text='{} sized of {} successfully stored'
''.format(filename, size))
解决OOM错误
最新推荐文章于 2024-07-16 10:47:17 发布