返回JSON和文件 [英] Return JSON and a File

查看:64
本文介绍了返回JSON和文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何返回JSON响应和文件响应:

How can I return a JSON response and a file response:

现在我这样做:

runNumber = "A0001"
response = None
try:
    response = make_response("Line One\r\nLine Two\r\n")
    response.headers["Content-Disposition"] = "attachment; filename=" + runNumber + ".txt"
except MyCustomException as e:
    response = jsonify(error=e.value, runnumber=runNumber)
except:
    raise
return(response)

但这仅允许我返回JSON或文件.在某些情况下,我想同时退货.

But that only allows me to return JSON OR a File. In some cases, I want to return both.

我要返回JSON和文件的情况是,当出现关于文件内容的警告时,用户在使用文件之前应检查该文件.

[edit:] The case where I want to return JSON and a file is when there is a warning about the file contents that the user should check before using the file.

如果这不可能,我将在文件内容中添加警告.

If this is not possible, I will add the warning to the contents of the file.

推荐答案

您不能只返回两个响应.您只能返回一个.

You cannot just return two responses. You get to return just the one.

这意味着,如果您确实需要返回JSON和文件,则需要提出一种方案,该方案可以让您在 one 响应中返回两者并让客户端再次分离出文件和JSON部分.

That means that if you really need to return both JSON and a file you need to come up with a scheme that lets you return the two in one response and let the client separate out the file and JSON parts again.

对此没有标准.无论您想出什么,都需要仔细记录在案,以便客户明确处理.

There is no standard for this. Whatever you come up with will need to be carefully documented for your clients to handle explicitly.

您可以使用自定义标头来存储JSON数据,例如:

You could use a custom header to store the JSON data, for example:

response = make_response("Line One\r\nLine Two\r\n")
response.headers["Content-Disposition"] = "attachment; filename=" + runNumber + ".txt"
response.headers['X-Extra-Info-JSON'] = json.dumps(some_object)

或者您可以将文件内容放入JSON数据中.JSON并不是二进制数据的最佳格式,您可能需要先将二进制数据编码为Base64:

Or you could put the file contents in the JSON data. JSON isn't the greatest format for binary data, you may want to encode the binary data to Base64 first:

filedata = "Line One\r\nLine Two\r\n".encode('base64')
return jsonify(name=runNumber + '.txt', data=filedata)

或者您可以以POST multipart/form-data 正文起作用的方式创建多部分MIME文档.

Or you could create a multipart MIME document, in the same way that a POST multipart/form-data body works.

选择的内容取决于用例(使用哪种API的客户端)和数据的大小(JSON响应中的兆字节文件数据不太可行).

What you pick depends on your use-cases (what kind of clients are using your API) and the size of the data (megabytes of file data in a JSON response is not very workable).

这篇关于返回JSON和文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆