无服务器 Flask 应用程序在本地运行,部署在 AWS Lambda 上时生成错误

问题描述 投票:0回答:1

更新:我的感觉是,这是无服务器框架对 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
python flask python-imaging-library serverless-framework
1个回答
0
投票

我也有同样的问题。我通过在 API 网关设置中添加 multipart/form-data 解决了这个问题。

Binay Media Settings 中设置 multipart/form-data 允许文件实际写入流。

因此也应该解决你的问题,因为我可以看到你有相同的流程。

另外,不要忘记再次部署 API。 如果它不起作用,请告诉我,并添加详细信息(如果有)。

© www.soinside.com 2019 - 2024. All rights reserved.