python - 如何通过flask返回json文件而不保存在磁盘上?

标签 python json flask

这里我有一个字典,

dict1 = {'name':"max","age":20}

我想要做的是将 dict 保存到 json 文件中。

@bp_main.route('/download/json', methods=['GET'])
def get_sample_json_file():
    dict1 =  {'name':"max","age":20}
    return ???

我现在所做的是将 dict1 保存到一个真正的 json 文件中,并使用flask send_from_directory 返回该文件。如何避免将 dict1 保存到磁盘中?

最佳答案

这只会返回您拥有的字典,因此您不必将字典保存到文件中。

from flask import Response
import json


@bp_main.route('/download/json', methods=['GET'])
def get_sample_json_file():
    dict1 =  {'name':"max","age":20}
    return Response(json.dumps(dict1), status=200, mimetype='application/json')

您也可以尝试jsonify回复。但我更喜欢响应方式。

关于python - 如何通过flask返回json文件而不保存在磁盘上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62230134/

相关文章:

javascript - Ajax 有 5% 的时间失败,响应为 "error"

json - 在 swift : Invalid type in JSON write (OS_dispatch_data) 中格式化 JSON

python - 如何将 "inject"内存中的 SQLAlchemy sqlite3 数据库放入 Flask test_client?

python - flask 操作错误 : unable to open database file using sqlite3

python - 将积分分解为椭圆积分

没有标题的 Python csv

javascript - 使用javascript的Strapi日期格式

python - 控制台中的输入文本被程序的输出分成多行

python - 在 python/django 中打印阿拉伯字符

python - Flask:将用户重定向到 html 页面的特定部分