0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Flaskでraiseした時に、任意のエラーメッセージを返す方法。

Posted at

目的

flaskアプリケーションにおいて、なんらかの不正を検知した時に、raiseをしつつアクセス元にもエラーメッセージを返したい。

  • return make_response("message", 400)
  • raise Exeption("message")

この2つの処理を同時にやりたい。

コード

myexception.py
class MyException(Exception):
    def __init__(self, message, code):
        self.code = code
        self.message = message
server.py
from flask import Flask, make_response
from myexception import MyException

app = Flask(__name__)

# デバッグ用
some_check = False

@app.route("/", methods=["POST"])
def root():
    if some_check == True:
        #正常処理
        pass
    else:
        #異常発見
        raise MyException("400 error", 400)

    return make_response("ok",200)

@app.errorhandler(MyException)
def error_my_except(e):
    return make_response(e.message, e.code)

アクセス結果

$ gunicorn -b 0.0.0.0:5000 server:app
[2021-12-12 12:12:12 +0000] [32486] [INFO] Starting gunicorn 20.0.4
[2021-12-12 12:12:12 +0000] [32486] [INFO] Listening at: http://0.0.0.0:5000
[2021-12-12 12:12:12 +0000] [32486] [INFO] Using worker: sync
[2021-12-12 12:12:12 +0000] [32495] [INFO] Booting worker with pid: 32123
$ curl -X POST localhost:5000
400 error

raiseしながらresponseを返せました。 :smile:

参考ページ

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?