flask에서는 json encoder를 사용해서 json 응답을 보내줘야 한다.


@app.route("/getEmployeeList") def getEmployeeList(): try: # Initialize a employee list employeeList = [] # create a instances for filling up employee list for i in range(0,2): empDict = { 'firstName': 'Roy', 'lastName': 'Augustine'} employeeList.append(empDict) # convert to json data jsonStr = json.dumps(employeeList) except Exception ,e: print str(e) return jsonify(Employees=jsonStr)


https://codehandbook.org/create-json-using-python-flask/





그러나 flask에 flask-restful을 추가해 설치한후,, 아래와 같이 설정한다면..


from flask import Flask
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

class HelloWorld(Resource):
    def get(self):
        return {'hello': 'world'}

api.add_resource(HelloWorld, '/')

if __name__ == '__main__':
    app.run(debug=True)



그냥 기본 타입과 collection은 자동으로 json으로 변환한다. 그 이유가 멀까?


json.dump(aaa) 이런 코드가 필요없어서 참 좋았다.







https://github.com/flask-restful/flask-restful/blob/master/flask_restful/__init__.py#L474


make_response()에서 default decorator로 json을 출력한다.





아래 코드를 보면, indent 4칸에 newline으로 예쁘게 출력하는 코드가 있다. 


https://github.com/flask-restful/flask-restful/blob/master/flask_restful/representations/json.py


from __future__ import absolute_import
from flask import make_response, current_app
from flask_restful.utils import PY3
from json import dumps


def output_json(data, code, headers=None):
    """Makes a Flask response with a JSON encoded body"""

    settings = current_app.config.get('RESTFUL_JSON', {})

    # If we're in debug mode, and the indent is not set, we set it to a
    # reasonable value here.  Note that this won't override any existing value
    # that was set.  We also set the "sort_keys" value.
    if current_app.debug:
        settings.setdefault('indent', 4)
        settings.setdefault('sort_keys', not PY3)

    # always end the json dumps with a new line
    # see https://github.com/mitsuhiko/flask/pull/1262
    dumped = dumps(data, **settings) + "\n"

    resp = make_response(dumped, code)
    resp.headers.extend(headers or {})
    return resp






Posted by 김용환 '김용환'