【问题标题】:getting json response using requests object flask使用请求对象烧瓶获取 json 响应
【发布时间】:2014-08-20 06:37:22
【问题描述】:

网络服务

@app.route('/get-details')
def getDetails():    
   cur.execute("select * from employee")
   rows = cur.fetchall()
   columns = [desc[0] for desc in cur.description]
   result = []
   for row in rows:
           row = dict(zip(columns, row))
           #json_row=json.dumps(row)
           result.append(row)

   json_response=json.dumps(result)
   response=Response(json_response,content_type='application/json; charset=utf-8')
   response.headers.add('content-length',len(json_response))
   response.status_code=200
   return response

网络服务器

@app.route('/get-details')
def getDetails():
      r=requests.get('http://localhost:8084/get-details')
      return r.json() #error in this line, however r.text is rendering the result but in html

错误

Error on request:
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 177, in run_wsgi
    execute(self.server.app)
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 165, in execute
    application_iter = app(environ, start_response)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1820, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1403, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1478, in full_dispatch_request
    response = self.make_response(rv)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1577, in make_response
    rv = self.response_class.force_type(rv, request.environ)
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/wrappers.py", line 827, in force_type
    response = BaseResponse(*_run_wsgi_app(response, environ))
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/wrappers.py", line 57, in _run_wsgi_app
    return _run_wsgi_app(*args)
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/test.py", line 855, in run_wsgi_app
    app_iter = app(environ, start_response)
TypeError: 'list' object is not callable

如何处理从webservice返回的响应,并把它当作json对待?

r.text 返回 ["{\"username\" : \"abhi\", \"pass\" : 2087}"] 这是一个字符串对象 我不知道 r.json 将如何格式化结果,但我想要类似的东西:

[{"username" : "abhi", "pass" : 2087}] 我可以使用 this 来完成,但我需要一个 List 而不是 String 来执行此操作。

【问题讨论】:

  • 你应该做r.json()而不是r.json?
  • 另外,你真的应该在烧瓶中使用 jsonify 来做出 json 响应。它会让你的生活更轻松
  • @corvid 在这种情况下不是一个好主意,因为 jsonify 只接受顶级对象。在我们的例子中,它是一个列表,所以它不起作用。
  • return jsonify({'my_list': my_list}) ;)

标签: python json flask


【解决方案1】:

首先,使用.json() 而不是.json。

然后,我认为您对数据进行双重 json 编码。

尝试这样做:

for row in rows:
       row = dict(zip(columns, row))
       # REMOVED
       result.append(row)

json_response=json.dumps(result)
response=Response(json_response,content_type='application/json; charset=utf-8')
response.headers.add('content-length',len(json_response))
response.status_code=200
return response

获取详细信息

from flask import jsonify

@app.route('/get-details')
def getDetails():
      r=requests.get('http://localhost:8084/get-details')
      json_response=json.dumps(r.json())
      response=Response(json_response,content_type='application/json; charset=utf-8')
      response.headers.add('content-length',len(json_response))
      response.status_code=200
      return response

【讨论】:

  • 但是我得到 list object is not callable 错误,因为 r.json()
  • 我已经编辑了我的答案,因为它是一个产品代码,我无法粘贴整个内容。但是我已经添加了错误跟踪和我对代码所做的更改。
  • @user3089927 这是因为您尝试通过执行 return r.json() 来“呈现”列表。你必须像 Corvid 说的那样把它 jsonify。我将更新我的示例。
  • @Dragu- ValueError: 字典更新序列元素#0 的长度为 7; 2 是必需的,我之前调整了输出,但原始输出是 ["{\"username\": \"abhi\", \"uuid\": \"abcd\", \"hostname\": \"XYZ \", \"platform\": \"Windows\", \"cost\": null, \"last_seen\": \"2014-08-18 19:40:00\", \"pass\": 2087}”]。我虽然没有效果。
  • @user3089927 现在检查我的新编辑。它已经过测试并且可以正常工作。 jsonify 只接受顶级对象,但不是你的情况。因此,只需在这两种情况下使用 json.dumps() 即可:)
猜你喜欢
  • 2021-01-23
  • 2017-08-24
  • 2021-12-30
  • 2016-04-21
  • 1970-01-01
  • 1970-01-01
  • 2019-01-04
  • 1970-01-01
  • 2019-07-16
相关资源
最近更新 更多