Update: my sense is that this a bug in the Serverless framework's support for WSGI applications because I can deploy the identical code to AWS using Zappa and it works.
I have this bit of Flask code that works fine when run locally using the Flask dev server. I can send POST requests to the local dev server and it all works, but generates an error when I send POST requests to the same app when deployed on AWS using the Serverless framework. I would greatly appreciate thoughts on this problem.
The relevant portion of the stack trace generated by PIL's Image.open() is this:
File "/var/task/app.py", line 30, in media
img = Image.open(image)
File "/var/task/PIL/Image.py", line 2590, in open
% (filename if filename else fp))
OSError: cannot identify image file <FileStorage: 'clipart.png' ('image/png')>
Here's the code:
from flask import Flask, request
from PIL import Image
from io import BytesIO, StringIO
from werkzeug.utils import secure_filename
app = Flask(__name__)
app.debug=True
@app.route('/', methods=['GET', 'POST'])
def media():
response = ""
if request.method == 'POST':
try:
image = request.files['file']
# Variations tried with no difference:
# image = request.files['file'].read()
# image = request.files['file'].stream
# image = request.files['file'].stream.read()
if isinstance(image, str):
print("Trying to open the image with StringIO")
img = Image.open(StringIO(image))
elif isinstance(image, (bytes, bytearray)):
print("Trying to open the image with BytesIO")
img = Image.open(BytesIO(image))
else:
print("Trying to open the image without BytesIO or StringIO")
img = Image.open(image)
response = {}
response['shape'] = (img.size[0], img.size[1])
except Exception as e:
print("An exception occured: {}".format(e))
raise e
else:
print("Everything worked!")
else:
response = {"GET":"request"}
return response