【问题标题】:How can I return a json of files with python flask-restfull?如何使用 python flask-restful 返回一个 json 文件?
【发布时间】:2019-11-23 22:31:32
【问题描述】:

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

当我尝试在客户端访问 json 对象时,我收到此错误:

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

这就是我在烧瓶应用中所做的:

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

如何返回 json 文件?

【问题讨论】:

  • 什么是“json文件”?您究竟希望用户收到什么作为您问题中代码的响应?
  • 如果我只用一个文件做同样的事情而不将 send_file() 包装在 {} 中,我可以在前端使用 java 脚本访问该文件。

标签: python json flask flask-restful


【解决方案1】:

如果我只用一个文件做同样的事情而不将 send_file() 包装在 {} 中,我可以在前端使用 java 脚本访问该文件。

你的意思是:

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

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

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

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

在这里,您将返回带有键 'message' 和值 'File not found!' 的字典。 Flask 会将其转换为Response 对象,状态码为404

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

当您尝试返回此内容时:

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

send_file 返回的 Response 对象随后被 json 化,因此异常:

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


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

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

【讨论】:

  • 感谢您的解释。为什么我不使用 base64 编码?来自前端的 API 调用成本很高。
【解决方案2】:

我认为您的例外过于广泛。但要取回 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-22
    • 1970-01-01
    • 1970-01-01
    • 2016-07-04
    • 2017-11-27
    • 2019-09-20
    • 2014-10-29
    • 2021-09-15
    相关资源
    最近更新 更多