2016-12-20 3 views
-1

플라스크 질문으로 다시 여기로 돌아갑니다. 저는 초보자이며 reddit (코드 합법)에서 멋진 것들을 배웁니다. 여기 내 코드는 내가 지금 플라스크를 통해 로컬로 호스트하려고하는 API로부터 특정 정보를 얻었습니다. 내가 127.0.0.1:5000를 실행하면플라스크의 내부 서버 오류

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() 

내가 얻을 :

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 - 

이 코드는 플라스크 프레임 워크 외부에서 작동해야합니다.

+1

내가 (대신하지만 장고) 플라스크에 익숙하지 않은 오전 . 내 생각 엔 당신이 dict 형식의 객체'response'를 보내려고하고있다. 하지만 HTTP 응답을 보내야합니다. Flask API *에 대한 응답으로 dict을 보내는 방법에 대한 Google의 답변 * : [Flask 웹 프레임 워크를 사용하여 json을 반환하는 방법] (http://stackoverflow.com/a/13089975/2063361) –

답변

1

유효한 HTTP 응답을 반환해야합니다. 이렇게하려면 다음과 같이 jsonify를 사용할 수 있습니다

return jsonify(response) 

이 같은 jsonify을 가져올 것을 잊지 마십시오

from flask import jsonify 

jsonify()flask.Response() 개체를 반환합니다.

또한 json.dumps()를 사용할 수 있지만이 경우 당신은 http 상태 코드와 유효한 HTTP 응답을 반환하는 Content-Type 헤더를 추가해야합니다

return json.dumps(response), 200, {'content-type': 'application/json'}