aiohttp 服务器文件上传:request.post UnicodeDecodeError
aiohttp server file upload: request.post UnicodeDecodeError
我在 Flask 中有一个处理上传的二进制数据的网络服务:
@app.route('/v1/something', methods=['POST'])
def v1_something():
for name in request.files:
file = request.files[name]
file.read()
...
现在我正在将其重写为 AIOHTTP,但在文件处理方面遇到了一些问题。我的代码:
@routes.post('/v1/something')
async def v1_something(request):
files = await request.post()
for name in files:
file = files[name]
file.read()
...
我在行 await request.post()
:
处收到错误
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 14: invalid start byte
看起来 AIOHTTP 试图将给定的二进制文件作为文本读取。我怎样才能避免这种情况?
我决定阅读源代码,发现 request.post()
用于 application/x-www-form-urlencoded
和 multipart/form-data
,这就是它总是尝试将给定数据解析为文本的原因。我还发现我应该使用 request.multipart()
:
@routes.post('/v1/something')
async def v1_something(request):
async for obj in (await request.multipart()):
# obj is an instance of aiohttp.multipart.BodyPartReader
if obj.filename is not None: # to pass non-files
file = BytesIO(await obj.read())
...
我在 Flask 中有一个处理上传的二进制数据的网络服务:
@app.route('/v1/something', methods=['POST'])
def v1_something():
for name in request.files:
file = request.files[name]
file.read()
...
现在我正在将其重写为 AIOHTTP,但在文件处理方面遇到了一些问题。我的代码:
@routes.post('/v1/something')
async def v1_something(request):
files = await request.post()
for name in files:
file = files[name]
file.read()
...
我在行 await request.post()
:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 14: invalid start byte
看起来 AIOHTTP 试图将给定的二进制文件作为文本读取。我怎样才能避免这种情况?
我决定阅读源代码,发现 request.post()
用于 application/x-www-form-urlencoded
和 multipart/form-data
,这就是它总是尝试将给定数据解析为文本的原因。我还发现我应该使用 request.multipart()
:
@routes.post('/v1/something')
async def v1_something(request):
async for obj in (await request.multipart()):
# obj is an instance of aiohttp.multipart.BodyPartReader
if obj.filename is not None: # to pass non-files
file = BytesIO(await obj.read())
...