0

I have a web service in Flask which processes uploaded binary data:

@app.route('/v1/something', methods=['POST'])
def v1_something():
    for name in request.files:
        file = request.files[name]
        file.read()
        ...

Now I'm rewriting it to AIOHTTP, but having some problem with files processing. My code:

@routes.post('/v1/something')
async def v1_something(request):
    files = await request.post()
    for name in files:
        file = files[name]
        file.read()
        ...

I get an error at the line await request.post():

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 14: invalid start byte

Looks like AIOHTTP tries to read given binary as a text. How can I prevent this?

AivanF.
  • 1,134
  • 2
  • 23
  • 52

1 Answers1

1

I decided to read the source code and found that request.post() intended for application/x-www-form-urlencoded and multipart/form-data, that's why it always tries to parse given data as a text. I also found that I should use 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())
            ...
AivanF.
  • 1,134
  • 2
  • 23
  • 52