更新:我的感觉是,这是无服务器框架对 WSGI 应用程序支持中的一个错误,因为我可以使用 Zappa 将相同的代码部署到 AWS 并且它可以工作。
我有一段 Flask 代码,在使用 Flask 开发服务器本地运行时工作正常。我可以向本地开发服务器发送 POST 请求,一切正常,但当我使用无服务器框架部署在 AWS 上时向同一应用程序发送 POST 请求时,会生成错误。我非常感谢对这个问题的想法。
PIL 的 Image.open() 生成的堆栈跟踪的相关部分是这样的:
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')>
这是代码:
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