【问题标题】:Send JSON file in response to a request, Flask发送 JSON 文件以响应请求,Flask
【发布时间】:2020-04-17 10:25:40
【问题描述】:

我有一个端点,它从请求中接收文本文件,烧瓶服务器处理该文本文件,现在需要发送一个应该是 json 文件的响应。我已经阅读并执行了接收到的 txt 文件的操作,现在当我通过 jsonify 发送 dict 时,我在终端中得到了这个。

响应 444 字节 [200 OK]

如何获取 json 文件,或者是否有任何其他方式发送 JSON 文件作为响应?由于我无法控制将发送请求的服务器,因此我需要一种发送 JSON 文件的方法。

处理响应的代码

@app.route('/automated_testing', methods=['GET','POST'])
def getfile():
    if request.method == 'POST':
        for file in request.files:
            links = request.files[file].read()
            #Since a byte sized object is returned
            links = [links.decode('utf8').strip()]
            links = links[0].split("\n")

        res = dict()
        for i in links:
            f = FlarePredictor(i)
            res[i] = f[0]

        print(jsonify(res), file=sys.stderr)
        return jsonify(res)
    else:
        return "GET REQ"

    return "Hi"

用于发送请求的代码

import requests

with open('test.txt', 'rb') as f:
    r = requests.post('http://127.0.0.1:5000/automated_testing', files={'test.txt': f})

【问题讨论】:

    标签: python json flask request response


    【解决方案1】:

    requests supports JSON out-of-the-box:

    json = r.json()
    

    现在json 将是一个包含数据的常规 Python 字典。

    【讨论】:

    • 现在,它给出 JSONDecodeError: Expecting value: line 1 column 1 (char 0)。我已经打印了 jsonified 的字典,它不是空的。
    • @YatinGupta,你收到的r.content 是什么?
    • @YatinGupta,这就是问题的原因!顺便说一句,根据您发布的代码,return "Hi" 将永远无法到达。请发布您正在运行的实际代码
    • r.json() 有效!抱歉,我评论了返回调试,忘记取消评论。谢谢!
    猜你喜欢
    • 2014-12-08
    • 2014-05-26
    • 2016-06-19
    • 2020-11-19
    • 1970-01-01
    • 2018-04-05
    • 2012-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多