zappa / Zappa

Serverless Python
https://zappa.ws/zappa
MIT License
3.35k stars 362 forks source link

Binary Support Not Working for Flask Application #1263

Closed valeriozhang closed 1 year ago

valeriozhang commented 1 year ago

Context

I am trying to serve byte responses from my zappa flask app. I enabled binary content types on my API gateway but i am still getting the error UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte when i run zappa tail

Expected Behavior

I should be able to receive byte responses from my flask API Gateway

Actual Behavior

receiving UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte error

Possible Fix

(https://docs.aws.amazon.com/apigateway/latest/developerguide/lambda-proxy-binary-media.html)

Steps to Reproduce

@app.route('/') def get_bytes_obj(path, format): try: return requests.get("https://www.google.com").content except Exception as e: print(e)

Your Environment

monkut commented 1 year ago

This may be a flask issue. By default I believe that flask attempts to return text/json as the response.

If you want to respond to your request with binary data, you need to prevent flask from attempting to convert the response content to text. I believe send_file can be used to return a binary response.

You can determine if this is a zappa issue by running flask locally and confirming that the error does not occur.

valeriozhang commented 1 year ago

Error does not occur locally, only when deployed to lambdas and api gateway.

monkut commented 1 year ago

Can you provide the traceback with line numbers?

valeriozhang commented 1 year ago

I did this instead and this worked!! just needed to wrap the response object

@app.route('/test.png') def get_test_png(): r = requests.get("https://www.google.com").content return Response( r.content, status=r.status_code, content_type=r.headers['content-type'], )

monkut commented 1 year ago

Closing this as it appears to be resolved by adjusting the response in the flask app.