如何使用 python flask-restful return json 文件?

How can I return a json of files with python flask-restfull?

我正在尝试使用 flask restfull 和 send_file 在 json 对象中发送两个文件。

当我尝试访问客户端的 json 对象时,出现此错误:

TypeError: Object of type 'Response' is not JSON serializable

这就是我在 Flask 应用程序中所做的:

class Download(Resource):
    def get(self):
        try:
            return {"file1" : send_file('uploads/kode.png'), "file2" : send_file('uploads/kode.png')}, 200
        except:
            return {"message" : "File not found!"}, 404

如何 return 一个 json 文件?

我认为你的例外范围太广了。但是要取回 json 对象,导入 json 及其 object.json()

import json
try:
    return file.json()
except Exception as e:
    print(e) 

或者您可以从 flask

导入 json 库
from flask import jsonify
def myMethod():
    ....
    response = jsonify(data)
    response.status_code = 200 # or 400 or whatever
    return response

If I do the same thing with only one file without wrapping the send_file() in {}, I can access that file on the front end with java script.

你的意思是:

return send_file('path/to/file.png')

这行得通,因为 Flask 的 send_file 函数实际上 return 是一个 Response 对象。

这也是有效代码(as of flask version 1.1.0):

return {"message" : "File not found!"}, 404

在这里,您正在 return 使用键 'message' 和值 'File not found!' 编辑字典。 Flask 会将其转换为 Response 对象,状态码为 404.

该词典会自动 jsonified (as of flask version 1.1.0)

当您尝试 return 时:

return {"file1" : send_file('uploads/kode.png')}, 200

send_file 编辑的 Response 对象 return 然后被 jsonified,因此异常:

TypeError: Object of type 'Response' is not JSON serializable


最明显的方法是前端应该为每个图像向服务器发出一个单独的请求,传递某种 ID,然后 Flask 路由函数应该 obtain 并使用它来计算文件路径,然后最终:return sendfile(filepath).

如果你真的想在一个 JSON 响应中发送多张图片,你可以查看 base64 encoding the image 并制作一个 data_uri 可以 JSON 序列化的字符串。但是,除非您真的需要将数据作为 JSON 传递,否则前一个选项可能是首选。