Python Flask-带有蓝图的错误处理

我正在使用flask,并且按功能有我的软件包,并且正在使用蓝图,这很好用,但是我希望有一个全局404和错误页面,它位于任何特定的功能包之外。

当我触发404烧瓶时,仍然使用默认的404处理程序来处理此问题,但我没有得到自定义模板。下面是我的代码:

初始化 .py

# Define the WSGI application object
app = flask(__name__)

# Load Configuration
app.config.from_object('config')

from .user.route import mod_user as user_module
from .route.error_handler import mod_error as error_module

# Register blueprints
app.register_blueprint(user_module)
app.register_blueprint(error_module)

error_handler.py

import traceback

from flask import flask,render_template,Blueprint

mod_error = Blueprint('error',__name__,template_folder='templates')


@mod_error.errorhandler(404)
def not_found(e):
    print(e)
    return render_template('404.html')


@mod_error.errorhandler(Exception)
def general_error(e):
    print(e)
    print(traceback.format_exc())
    return render_template('error.html')

我的功能路线在project.user.route.py

中定义

全局路由\错误处理程序位于project.route.error_handler.py

全局错误模板位于project.templates

linxierhebei 回答:Python Flask-带有蓝图的错误处理

我设法解决了这个问题,这很简单,当我从一个脚本中的所有内容转移到使用蓝图,并创建了错误处理模块时,我认为我需要在注释中使用模块名称:

@mod_error.errorhandler(404)

这样做的原因是因为这是我在控制器中针对用户功能执行的操作:

@mod_user.route('/read',methods=['POST','GET'])

下面是我需要做的,它是导入我的应用程序对象,然后将其用于错误处理程序功能:

import traceback

from flask import Flask,render_template,Blueprint
from .. import app

mod_error = Blueprint('error',__name__,template_folder='templates')


@app.errorhandler(404)
def not_found(e):
    print(e)
    return render_template('404.html')


@app.errorhandler(Exception)
def general_exception(e):
    print(e)
    print(traceback.format_exc())
    return render_template('error.html')

这现在可以在我的任何功能包之外的全局级别处理所有错误,我希望实现ControllerAdvice的效果,该效果可以处理Spring MVC中所有控制器的所有异常。

本文链接:https://www.f2er.com/3152950.html

大家都在问