【问题标题】:Extracting JSON data from flask response object [duplicate]从烧瓶响应对象中提取 JSON 数据
【发布时间】:2021-01-23 15:11:44
【问题描述】:

如何提取 Flask 返回的 JSON 数据?

后端:

response_obj = {
        'status': 'fail',
        'message': 'Invalid Payload'
    }
return jsonify(response_obj), 500

前端:

import requests

data = # some json data here
response = requests.post('http://18.133.238.8/auth/login', json=data)

我试过了:

print(dir(response))

这给了我:

...
...
__', '__nonzero__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_content', '_content_consumed', '_next', 'apparent_encoding', 'close', 'connection', 'content', 'cookies', 'elapsed', 'encoding', 'headers', 'history', 'is_permanent_redirect', 'is_redirect', 'iter_content', 'iter_lines', 'json', 'links', 'next', 'ok', 'raise_for_status', 'raw', 'reason', 'request', 'status_code', 'text', 'url']

这提示我使用:

print(response.json)

或:

print(response.json())

我只是得到错误。如何从响应中获取 JSON 数据?

【问题讨论】:

  • response.json() 应该是正确的。除非您向我们详细说明您遇到的错误,否则我们无法为您提供帮助。
  • 我猜这是因为 500 错误,您正在返回 return jsonify(response_obj), 500。如果没问题,那么你可以跳过自定义状态码,因为jsonify 默认返回 200。也可以试试print(response.content) 这可能会提供一些线索或print(response.status_code)
  • 不,我故意退回500。它位于处理各种错误的代码块中。
  • @simkus response.content 工作得很好!所以我只是使用了错误的属性。谢谢@simkus!随意发布它作为解决方案。

标签: python flask


【解决方案1】:

试试这个方法:

from requests import request

response = request('POST', "<URL here>")
print(response.json())

【讨论】:

  • 我将 json 数据传递给 post 请求。我如何使用你的方式通过它?你的方式似乎没有接受json 参数。
猜你喜欢
  • 1970-01-01
  • 2019-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-26
  • 1970-01-01
  • 2017-11-01
  • 2018-09-27
相关资源
最近更新 更多