Life is Really Short, Have Your Life!!

ござ先輩の主に技術的なメモ

FlaskのBluePrintで404を指定することは出来ない

Flaskの仕様で、404のエラーハンドラーを blueprint 毎に定義することが出来ず、ちょっとハマった。

以下の公式にあるように、Flaskのアプリケーションそのものが、404になるURLがリクエストされた時にどのblueprintのエラーハンドラーを呼び出していいかわからんって書いてある。つまり、404と405はグローバルに定義しろってことらしい。

This is because the blueprint does not “own” a certain URL space, so the application instance has no way of knowing which blueprint error handler it should run if given an invalid URL.

Modular Applications with Blueprints — Flask Documentation (2.3.x)

@app.errorhandler(404)
@app.errorhandler(405)
def _handle_api_error(ex):
    if request.path.startswith('/api/'):
        return jsonify(error=str(ex)), ex.code
    else:
        return ex

初めてFlask触ったのが、2013年とかで、当時のバージョンは0.10だった。今は2.3か。それでも全然コアのアーキテクチャは変わらない。Flaskに学ぶことは多かった。