【问题标题】:Internal Server Error from Flask [duplicate]来自 Flask 的内部服务器错误 [重复]
【发布时间】:2016-12-20 20:09:04
【问题描述】:

带着一个烧瓶问题再次回到这里。我是一个初学者,从 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 -

我应该提到这段代码在烧瓶框架之外工作!

【问题讨论】:

  • 我不熟悉flask(而是Django)。我的猜测是您正在尝试发回 dict 类型对象response 。但是您需要发送 HTTP 响应。您可以在 how to send dict as response to Flask API 上搜索结果:How to return json using Flask web framework

标签: python api flask


【解决方案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'}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 2023-03-14
    相关资源
    最近更新 更多