4

次のコードがあります。http ハンドラー関数(func1)と RESTful API(func2)があり、URL/test1/test2. 処理されていないすべての例外がjsonifyされ、応答として返されるようにするために(exception_handler)装飾された例外ハンドラー関数があります。app.errorhandler()

from flask import Flask, jsonify
from flask.ext.restful import Resource, Api

app = Flask(__name__)
api = Api(app)

@app.errorhandler(Exception)
def exception_handler(e):
  return jsonify(reason=e.message), 500

@app.route("/test1", methods=["GET"])
def func1():
    raise Exception('Exception - test1')

class func2(Resource):
  def get(self):
    raise Exception('Exception - test2')

api.add_resource(func2, '/test2')

if __name__ == "__main__":
    app.run(debug=True)

例外メッセージを含む JSON を使用して未処理の例外を HTTP 応答に変換することは、通常の http ハンドラー関数では正常に機能しますfunc1が、RESTful API (リソースを使用して作成) では同じことが機能しませんfunc2

以下は、期待どおりに正常に動作しfunc1ます。

$ curl http://127.0.0.1:5000/test1 -X GET
{
  "reason": "Exception - test1"
}

の代わりfunc2{"message": "Internal Server Error", "status": 500}{"reason": "Exception - test2"}

$ curl http://127.0.0.1:5000/test2 -X GET
{
    "message": "Internal Server Error",
    "status": 500
}

問題は、RESTful API で未処理の例外が JSON に変換されない理由app.errorhandlerです。またはこれを行う他の方法はありますか?

4

2 に答える 2

4

これは、エンドポイントの特定のロジックと他のエンドポイントのデフォルトの動作を持つFlask-Restfulmonkeypatchのデフォルトのためです。Flask.handle_user_exceptionFlask-Restful

于 2013-10-04T19:00:40.670 に答える