将JSON响应从请求调用传递给Flask响应

时间:2015-09-08 15:46:45

标签: python json flask python-requests

我有一个函数向外部URL发出请求并返回解码的JSON响应。我想添加一个Flask视图来进行此调用并在我的应用程序中返回JSON响应。该功能在IPython笔记本中有效,但在Flask中没有,我得到TypeError: 'dict' object is not callable。如何通过Flask从请求中返回JSON响应?

def get_one_day(year, month, day):     
    url = 'http://api.wunderground.com/api/' + API_KEY + '/history_' + year + month + day +'/geolookup/q/Beijing/Beijing.json'
    cnt = requests.get(url)
    js = cnt.json()
    return js       

@app.route('/')
def download():    
    response = make_response(get_one_day('2014', '01', '01'))
    return response
File "/anaconda/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/anaconda/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/anaconda/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/anaconda/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/anaconda/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/anaconda/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/anaconda/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/anaconda/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/jm/Dev/weather/weather.py", line 40, in download
response = make_response(get_one_day('2014', '01', '01'))
File "/anaconda/lib/python2.7/site-packages/flask/helpers.py", line 183, in make_response
return current_app.make_response(args)
File "/anaconda/lib/python2.7/site-packages/flask/app.py", line 1577, in make_response
rv = self.response_class.force_type(rv, request.environ)
File "/anaconda/lib/python2.7/site-packages/werkzeug/wrappers.py", line 841, in force_type
response = BaseResponse(*_run_wsgi_app(response, environ))
File "/anaconda/lib/python2.7/site-packages/werkzeug/test.py", line 867, in run_wsgi_app
app_rv = app(environ, start_response)
TypeError: 'dict' object is not callable

1 个答案:

答案 0 :(得分:4)

您没有返回有效的回复。 Flask需要一个字符串,元组或Response对象,但是你直接返回JSON数据(一个字典)。而不是解码JSON,只需将其作为响应传递。

return app.response_class(cnt.content, mimetype='application/json')

或使用jsonify将dict转换为JSON响应。

from flask import jsonify

js = cnt.json()
return jsonify(js)