ASH84

Software Engineer/Developer, co-founder of Payhere. Ex-Banksalad. Intereseted in iteroperability, bootstrap company, writting.

(flask) JSON 데이터 받기 및 예외처리

created:2016-12-06
updated:2017-09-29
edit

flask 에서 json 데이터를 받아서 처리할 때 reqeust.get_json() 혹은 request.json 을 이용할 수 있는데, mime type을 application/json 타입으로 보내는데, {} 없이 빈 JSON 문자열 조차도 안 보내는 경우가 있을수가 있다.

from flask import Flask  
from flask import request  
app = Flask(__name__)

@app.route("/test", methods=['POST'])
def test():  
    print request.json #request.get_json()
    return "Hello World!"

이런 경우 flask 에서는 400 bad request 를 응답값으로 보낸다. 보내는 이유는 parsing fail이 발생하고 on_json_loading_failed(e) 함수가 실행되게 된다. 이 함수는 JSON Decode 실패 시 400 Bad Request를 보내느 것이 기본 구현으로 되어 있다. JSON parsing fail 이 나더라도 400 Bad Request 외의 다른 행동을 정의하기 위해서는 아래와 같은 방법을 사용하면 된다.

1. on_json_loading_failed() 재정의 하기

def on_json_loading_failed_return_dict(e):  
    return {}


@app.route("/test", methods=['POST'])
def test():  
    request.on_json_loading_failed = on_json_loading_failed_return_dict
    print request.get_json()
    return "Hello World!" 

2. get_json() silent 파라미터 활용

print request.get_json(silent=True)  

Parameters:

어떤 방식을 선호하는지는 개인이나 프로젝트 성격에 따라 다를것 같다. 모든 API가 JSON 으로 데이터를 전달하는 방식이라면, on_json_loading_failed() 함수를 재정의하고 decorator 등을 활용하는게 좋을것 같다. (필자 역시 최근의 프로젝트에서 그렇게 활용했다.)

참고로 flask 0.11 버전에서는 is_json 이 추가되었는데 이것은 parsing fail 을 감지하는 것이 아니라, mimetype 이 application/json 인지 아닌지를 True | False 로 반환하는 역할을 한다.


#dev  #FLASK  #Python  #get_json()  #on_json_loading_failed