簡體   English   中英

Python/Flask 應用程序中注冊的錯誤處理程序不起作用

[英]Registered error handler in Python/Flask application does not work

我在 main.py 中使用以下代碼創建了一個 Python/Flask 應用程序:

import json

from flask import Flask, jsonify
from werkzeug.exceptions import HTTPException, default_exceptions

from blueprints import test

def create_app(config_filename=None) -> Flask:
   """Application factory function
   """
   app = Flask(__name__, instance_relative_config=True)
   if config_filename:
       app.config.from_pyfile(config_filename)

   for exc in default_exceptions:
       app.register_error_handler(exc, handle_error)        

   register_blueprints(app)
   return app

def handle_error(error):
   code = 500
   if isinstance(error, HTTPException):
       code = error.code
   return jsonify(error='error', code=code)    


def register_blueprints(app: Flask):
   """Register blueprints
   """
   app.register_blueprint(test.bp)


def handle_exception(ex: HTTPException):
   """Return JSON instead of HTML for HTTP errors."""
   # start with the correct headers and status code from the error
   response = ex.get_response()
   # replace the body with JSON
   response.data = json.dumps({
       "code": ex.code,
       "error": ex.name,
       "message": ex.description,
   })
   response.content_type = "application/json"
   return response


if __name__ == '__main__':
   main_app = create_app()
   main_app.run(host='0.0.0.0', port=80, debug=True, threaded=False)

test.py 藍圖的源代碼是:

from flask import Blueprint, jsonify, request
from werkzeug.exceptions import HTTPException, default_exceptions

bp = Blueprint('blabla', __name__)

@bp.route('/blabla', methods=['POST'])
def blabla():
   """Test blueprint
   """
   raise MyException()

class MyException(HTTPException):

   code = 409
   name = 'My Exception'
   description = 'My Exception'

不幸的是,當我執行端點時,main.py 中定義的方法不處理異常

我什至決定並嘗試在藍圖中注冊錯誤處理程序,但結果是一樣的——方法不處理異常。

這是修改后的 test.py

from flask import Blueprint, jsonify, request
from werkzeug.exceptions import HTTPException, default_exceptions

bp = Blueprint('blabla', __name__)

@bp.errorhandler(409)
def error_handler(e):
    return handle_error(e)

@bp.route('/blabla', methods=['POST'])
def blabla():
    """Test blueprint
    """
    raise MyException()

def handle_error(error):
    code = 500
    if isinstance(error, HTTPException):
        code = error.code
    return jsonify(error='error', code=code)

class MyException(HTTPException):

    code = 409
    name = 'My Exception'
    description = 'My Exception'

有人可以告訴我我的錯誤是什么嗎? 為什么錯誤方法不處理異常?

此示例直接來自flask ,它在您的代碼方面略有不同,例如,在@app.errorhandler(404)裝飾器中,他們檢查請求用戶如下request.path.startswith('') ,也許這不是錯誤的來源,但我建議您仔細閱讀示例和說明,以使用藍圖錯誤處理程序處理錯誤

from flask import jsonify, render_template

# at the application level
# not the blueprint level
@app.errorhandler(404)
def page_not_found(e):
    # if a request is in our blog URL space
    if request.path.startswith('/blog/'):
        # we return a custom blog 404 page
        return render_template("blog/404.html"), 404
    else:
        # otherwise we return our generic site-wide 404 page
        return render_template("404.html"), 404

@app.errorhandler(405)
def method_not_allowed(e):
    # if a request has the wrong method to our API
    if request.path.startswith('/api/'):
        # we return a json saying so
        return jsonify(message="Method Not Allowed"), 405
    else:
        # otherwise we return a generic site-wide 405 page
        return render_template("405.html"), 405

實際上它出來了,錯誤處理程序必須在藍圖之后注冊:

def register_blueprints(app: Flask):
    app.register_blueprint(test.bp)
    
    app.register_error_handler(HTTPException, handle_exception)

def handle_exception(ex: HTTPException):
    """Return JSON instead of HTML for HTTP errors."""
    # start with the correct headers and status code from the error
    response = ex.get_response()
    # replace the body with JSON
    response.data = json.dumps({
        "code": ex.code,
        "error": ex.name,
        "message": ex.description,
    })
    response.content_type = "application/json"
    return response

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM