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을 추가해 설치한후,, 아래와 같이 설정한다면..
그냥 기본 타입과 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'python' 카테고리의 다른 글
| [python] subprocess- paramiko 예시 (부제 - TypeError: startswith first arg must be bytes or a tuple of bytes, not str 해결하기) (0) | 2018.12.28 |
|---|---|
| [python] pre-commit 추가하기 (0) | 2018.11.09 |
| flask에서 개발할 때 jsonify, json.dump 없이 json 응답 보내기 (0) | 2018.11.08 |
| python으로 해결하는 JSONP 파싱 예시 (0) | 2018.11.06 |
| pip 설치 모듈 확인하기 (0) | 2018.10.25 |
| [python] 모듈 프로그래밍 환경 설정 (ModuleNotFoundError 에러 해결) (0) | 2018.10.20 |



댓글을 달아 주세요