再回到这里,有一个烧瓶问题。我是初学者,从reddit(如何合法代码)学习一些很棒的东西。 这是我的代码,我从API中获取了某些信息,我现在正试图通过烧瓶本地托管。
from flask import Flask, render_template
import httplib
import json
app = Flask(__name__)
@app.route('/')
def index():
connection = httplib.HTTPConnection('api.football-data.org')
headers = {'X-Auth-Token': 'this is my api token here', 'X-Response-Control': 'minified'}
connection.request('GET', '/v1/competitions/426/leagueTable', None, headers)
response = json.loads(connection.getresponse().read().decode())
return response
if __name__ == '__main__':
app.run()
当我运行127.0.0.1:5000时,我得到:
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
这是我服务器告诉我的内容!
MacBooks-MBP:Football macbookpro13$ python Footy_Web.py
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
[2016-12-20 13:58:17,493] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/flask/app.py", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "/Library/Python/2.7/site-packages/flask/app.py", line 1642, in full_dispatch_request
response = self.make_response(rv)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1746, in make_response
rv = self.response_class.force_type(rv, request.environ)
File "/Library/Python/2.7/site-packages/werkzeug/wrappers.py", line 847, in force_type
response = BaseResponse(*_run_wsgi_app(response, environ))
File "/Library/Python/2.7/site-packages/werkzeug/wrappers.py", line 57, in _run_wsgi_app
return _run_wsgi_app(*args)
File "/Library/Python/2.7/site-packages/werkzeug/test.py", line 871, in run_wsgi_app
app_rv = app(environ, start_response)
TypeError: 'dict' object is not callable
127.0.0.1 - - [20/Dec/2016 13:58:17] "GET / HTTP/1.1" 500 -
我应该提到这个代码在烧瓶框架之外工作!
答案 0 :(得分:1)
您需要返回有效的HTTP
回复。为此,您可以使用jsonify
,如下所示:
return jsonify(response)
不要忘记像这样导入jsonify
:
from flask import jsonify
jsonify()
会返回flask.Response()
个对象。
您也可以使用json.dumps()
,但在这种情况下,您需要添加http
状态代码和Content-Type
标头以返回有效的HTTP
响应:
return json.dumps(response), 200, {'content-type': 'application/json'}