Python 无服务器Flask应用程序在本地工作,在AWS Lambda上部署时生成错误
更新:我的感觉是,这是无服务器框架对WSGI应用程序的支持中的一个缺陷,因为我可以使用Zappa将相同的代码部署到AWS,并且它可以工作 我有一些Flask代码,当使用Flask dev服务器在本地运行时,这些代码可以很好地工作。我可以向本地dev服务器发送POST请求,这一切都可以正常工作,但是当我使用无服务器框架在AWS上部署时向同一应用发送POST请求时,会生成一个错误。我将非常感谢您对这个问题的思考 PIL的Image.open()生成的堆栈跟踪的相关部分如下:Python 无服务器Flask应用程序在本地工作,在AWS Lambda上部署时生成错误,python,flask,python-imaging-library,serverless-framework,Python,Flask,Python Imaging Library,Serverless Framework,更新:我的感觉是,这是无服务器框架对WSGI应用程序的支持中的一个缺陷,因为我可以使用Zappa将相同的代码部署到AWS,并且它可以工作 我有一些Flask代码,当使用Flask dev服务器在本地运行时,这些代码可以很好地工作。我可以向本地dev服务器发送POST请求,这一切都可以正常工作,但是当我使用无服务器框架在AWS上部署时向同一应用发送POST请求时,会生成一个错误。我将非常感谢您对这个问题的思考 PIL的Image.open()生成的堆栈跟踪的相关部分如下: 您是否打包了PIL包并将
您是否打包了PIL包并将其上载到AWS lambda?是的,因为无服务器框架为您完成了所有这些。如果您在API网关后面安装了PIL包,这可能就是问题所在。如果我们上传了multipart,我们就无法让它工作,当我们在json正文中使用base64 str时,它工作得很好(但您需要对它进行解码)。也许这会有所帮助:它确实在API网关后面,但我没有选择使用base64编码,因为Trix编辑器(我在前端使用)使用多部分/表单数据发布文件。我尝试在API网关控制台的二进制类型部分设置多部分/表单数据,但这并没有改变任何事情。谢谢你的建议。你是否打包了PIL包并将其上传到AWS lambda?是的,因为无服务器框架可以为你完成所有这些。如果你在API网关后面安装了它,这可能就是问题所在。如果我们上传了multipart,我们就无法让它工作,当我们在json正文中使用base64 str时,它工作得很好(但您需要对它进行解码)。也许这会有所帮助:它确实在API网关后面,但我没有选择使用base64编码,因为Trix编辑器(我在前端使用)使用多部分/表单数据发布文件。我尝试在API网关控制台的二进制类型部分设置多部分/表单数据,但这并没有改变任何事情。谢谢你的建议。
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