Flask でレスポンスを返す方法はいくつかある。単純な文字列を返すだけでなく、ステータスコードやヘッダーを指定することもできる。
文字列を返す
最も単純な方法は、文字列をそのまま返すことである。
@app.route('/')
def index():
return 'Hello, World!'
この場合、ステータスコードは 200、Content-Type は text/html になる。
ステータスコードの指定
タプルで返すと、ステータスコードを指定できる。
@app.route('/not-found')
def not_found():
return 'Page not found', 404
@app.route('/created')
def created():
return 'Resource created', 201
第2要素にステータスコードを指定する。
ヘッダーの指定
第3要素に辞書を渡すと、レスポンスヘッダーを設定できる。
@app.route('/custom')
def custom():
headers = {'X-Custom-Header': 'MyValue'}
return 'Custom response', 200, headers
Response オブジェクト
より細かい制御が必要な場合は make_response を使う。
from flask import make_response
@app.route('/response')
def response_example():
resp = make_response('Hello')
resp.status_code = 200
resp.headers['X-Custom'] = 'Value'
resp.set_cookie('session_id', 'abc123')
return resp
make_response で Response オブジェクトを作成し、属性やメソッドで各種設定を行える。
主要なステータスコード
| 200 | OK(成功) |
| 201 | Created(リソース作成成功) |
| 204 | No Content(成功したが返すデータなし) |
| 400 | Bad Request(リクエストが不正) |
| 401 | Unauthorized(認証が必要) |
| 403 | Forbidden(アクセス禁止) |
| 404 | Not Found(リソースが存在しない) |
| 500 | Internal Server Error(サーバーエラー) |