LoginSignup
15
16

More than 3 years have passed since last update.

PythonフレームワークFlask エラーハンドリング メモ

Posted at
  • PythonフレームワークFlaskのエラーハンドリング方法についてメモする。

Flask エラーハンドリング

  • アプリケーションで発生した例外を処理するためにエラーハンドラーを登録する。
  • 例外発生時に、その例外のエラーハンドラーが登録されているかを参照し、登録されている場合に対応する関数を呼び出す。

エラーハンドラーの登録方法

errorhandler()デコレーター

  • errorhandler()を使って関数を修飾(decorating)してエラーハンドラーを登録する。
@app.errorhandler(werkzeug.exceptions.BadRequest)
def handle_bad_request(e):
    return 'bad request!', 400

register_error_handler関数

app.register_error_handler(400, handle_bad_request)

例外の送出

raise

  • Exceptionのサブクラスを指定
from flask import abort
from werkzeug.exceptions import NotFound
app = Flask(__name__)
app.errorhandler(NotFound)
def not_found(e):
    return "handling NotFound"

app.route('/test/raise/notfound')
def raise_not_found():
    raise NotFound

abort

  • werkzeug.exceptions.HTTPExceptionのサブクラスの例外をraiseする。
  • ステータスコードのみ指定。
from flask import abort
from werkzeug.exceptions import NotFound
app = Flask(__name__)
app.errorhandler(NotFound)
def not_found(e):
    return "handling NotFound"

app.route('/test/abort/notfound')
def abort_not_found():
    abort(404)

動作確認

全体

import json
from flask import Flask, jsonify, make_response, request, Response
from werkzeug.exceptions import NotFound,BadRequest,InternalServerError
app = Flask(__name__)

@app.route('/test', methods=['POST'])
def post_test():
  try:
    req = request.get_json()
    name = req['name']
    res = {
        "id": 1,
        "name": name
      }
    return jsonify(res) 
  except Exception as e:
    abort(e.code)

@app.errorhandler(BadRequest)
@app.errorhandler(NotFound)
@app.errorhandler(InternalServerError)
def error_handler(e):
    res = jsonify({ 
                     "error": {
                          "name": error.name, 
                          "description": error.description 
                      }
                   })
    return res, e.code

if __name__ == "__main__":
  app.run(host='0.0.0.0')

リクエスト

POST /tes HTTP/1.1
Host: localhost:5000
Content-Type: application/json
Content-Length: 36

{
    "name":"test",
    "id":1
}

レスポンス

404 NOT FOUND

{
    "error": {
        "description": "The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.",
        "name": "Not Found"
    }
}

参考情報

15
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
16