【问题标题】:Flask send image with curl as json payloadFlask 发送带有 curl 的图像作为 json 有效负载
【发布时间】:2020-10-15 09:51:29
【问题描述】:

我有一个简单的带有文件上传功能的烧瓶 API 来发送图像:

from flask import request
from flask import Flask

app = Flask(__name__)

@app.route('/', methods=['POST'])
def upload_file():
    f = request.files['image']
    print(f.content_type)
    print(f.filename)
    # do something with the file
    # f.read() 
return("Done")
    
if __name__ == "__main__":
    app.run(debug=True, host='0.0.0.0', port=5000)

当我使用curl-F 选项发送图像时,我可以访问该文件: curl -XPOST localhost:5000 -F "image=@img.jpg"

但是如何使用-d 选项将图像作为有效负载发送到 json 文件中?如果我使用base64 对图像进行编码,将字符串放入 json 文件并使用-d 选项发送,它找不到我的图像:KeyError: 'image' 我尝试了不同的内容类型:

curl -XPOST localhost:5000 -d @img.json --header "Content-Type: application/json"

curl -XPOST localhost:5000 -d @img.json --header "Content-Type: image/jpeg"

我的image.json 看起来像这样:

{"image":"/9j/4AAQSkZJRgABAQEAS..."}

(用完整的字符串代替...

【问题讨论】:

    标签: python api flask curl file-upload


    【解决方案1】:

    如果您将数据作为 JSON 有效负载发送,则必须使用 request.json 来访问它们。 Flask docs for files attribute 状态,当enctype="multipart/form-data" 时该属性为非空。当您使用 -F 选项时,curl 将隐式设置 multipart/form-data 标头。

    但是对于 json 数据,您必须设置 --header "Content-Type: application/json",就像您在示例中一样。但是,您必须在服务器端检查request.mimetype。根据该检查,您将使用 filesjson 属性。以下是如何处理这两种情况的示例:

    from flask import request
    from flask import Flask
    
    app = Flask(__name__)
    
    @app.route('/', methods=['POST'])
    def upload_file():
        if request.mimetype == 'multipart/form-data':
            f = request.files['image']
            print(f.content_type)
            print(f.filename)
            # do something with the file
            # f.read() 
        else if request.mimetype == 'application/json':
            f = request.json['image']
            print(f)
            # decode f from Base64
        else:
            # handle other mimetypes or return that selected mimetype is not supported 
            print('Unsupported content-type')
      
        return("Done")
        
    if __name__ == "__main__":
        app.run(debug=True, host='0.0.0.0', port=5000)
    

    你使用的curl命令应该被正确处理:

    curl -XPOST localhost:5000 -d @img.json --header "Content-Type: application/json"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-25
      • 1970-01-01
      • 2014-07-21
      • 1970-01-01
      相关资源
      最近更新 更多