[英]how to read python flask jsonify response object
I have a python
function which returns Flask jsonify
object. 我有一个返回Flask jsonify
对象的python
函数。 When I try to read this returned json
object using get_json()
or even json()
it throws error. 当我尝试使用get_json()
甚至json()
读取此返回的json
对象时,会引发错误。 Here is my code: 这是我的代码:
from flask import jsonify
def funct1(par1):
if par1 == 'Hi':
return jsonify(result=1,msg='Hello')
else:
return jsonify(result=0,msg='Sorry')
def func2():
response = funct1('Hi')
rsp_js = response.get_json() # This throws error
print(rsp_js)
When I execute above I get error as Response object has no attribute get_json
. 当我在上面执行时,由于Response object has no attribute get_json
,我得到了错误。 I tried json()
as well but get the same error. 我也尝试了json()
,但是得到了同样的错误。 How can I read the returned jsonify object? 如何读取返回的jsonify对象?
NOTE : I have flask version 0.12.2 注意 :我的烧瓶版本为0.12.2
get_json
was not added to response objects in flask until version 1.0 . 直到版本1.0才将get_json
添加到flask的响应对象中。 In previous versions, you need to use get_data
: 在以前的版本中,您需要使用get_data
:
import json
json.loads(response.get_data().decode("utf-8"))
Having said this, I would caution you against calling route methods directly from other functions (except for testing), or returning response objects from non-route methods. 话虽如此,我提醒您不要直接从其他函数(测试除外)调用路由方法,也不要从非路由方法返回响应对象。
If you are attempting to test this method, you should consider using the test_client
: 如果尝试测试此方法,则应考虑使用test_client
:
with app.test_client() as client:
json.loads(client.get("the/url").get_data().decode("utf-8"))
# ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.