DEV Community

sunj
sunj

Posted on

Flask response

view 함수로부터 반환되는 값은 자동으로 response 객체로 변환된다. 만약 반환값이 문자열이라면 response body로 문자열과 200 OK 코드, text/html mimtype을 갖는 response객체로 변환된다. Flask에서 반환값을 response 객체로 변환하는 로직은 아래와 같다:

1. 만약 정확한 유형의 response객체가 반환된다면 그 객체는 그대로 뷰로부터 반환되어 진다.
2. 만약 문자열이 반환된다면, response객체는 해당 데이타와 기본 파라미터들을 갖는 reponse객체가 생성된다.
3. 만약 튜플이 반환된다면 튜플 안에 있는 아이템들이 추가적인 정보를 제공할 수 있다. 그런 퓨틀들은 지정된 폼 (response, status, headers) 이여야 하며, 그 중 적어도 하나의 아이템이 튜플 안에 있어야 한다. status 값은 statud code를 오버라이드하면 ` headers` 는 추가적인 정보의 list, dictionary가 될 수 있다.
4. 만약 위의 것들이 아무것도 적용되지 않는다면, Flask는 반환값이 유효한 WSGI application 이라고 가정하고 WSGI application을 response객체로 변환할 것이다.
Enter fullscreen mode Exit fullscreen mode

뷰 안에서 결과 response 객체를 찾기를 원한다면 make_response() 함수를 사용할 수 있다

@app.errorhandler(404)
def not_found(error):
    return render_template('error.html'), 404
Enter fullscreen mode Exit fullscreen mode
@app.errorhandler(404)
def not_found(error):
    resp = make_response(render_template('error.html'), 404)
    resp.headers['X-Something'] = 'A value'
    return resp
Enter fullscreen mode Exit fullscreen mode

참조 : https://flask-docs-kr.readthedocs.io/ko/latest/quickstart.html#id11

Top comments (0)