Skip to main content
 首页 » 编程设计

python之在 Flask 应用程序中重用样板代码

2025年05月04日15lvdongjie

我的许多 Flask 应用程序都有一些错误处理调用。例如,我的 404 响应是使用 @app.errorhandler 装饰器定义的:

@app.errorhandler(404) 
def page_not_found(e): 
    return jsonify({'status': 'error', 
                    'reason': '''There's no API call for %s''' % request.base_url, 
                    'code': 404}), 404 

由于我有大量的样板代码,我想将其放在一个公共(public)文件中并从一个地方继承或导入我的 Flask 应用程序。

是否可以从不同的模块继承或导入 Flask 样板代码?

请您参考如下方法:

当然有,但是您需要对注册进行参数化。

不使用装饰器,而是将注册移至函数:

def page_not_found(e): 
    return jsonify({'status': 'error', 
                    'reason': '''There's no API call for %s''' % request.base_url, 
                    'code': 404}), 404 
 
 
def register_all(app): 
    app.register_error_handler(404, page_not_found) 

然后导入 register_all 并使用您的 Flask() 对象调用它。

这使用了 Flask.register_error_handler()函数而不是装饰器。

要也支持蓝图,您需要等待 Flask 的下一个版本(包括 this commit ),或者直接使用装饰器函数:

app_or_blueprint.errorhandler(404)(page_not_found) 

对于其中的许多任务,您也可以使用蓝图,前提是您使用 Blueprint.app_errorhandler() :

common_errors = Blueprint('common_errors') 
 
 
@common_errors.errorhandler(404)     
def page_not_found(e): 
    return jsonify({'status': 'error', 
                    'reason': '''There's no API call for %s''' % request.base_url, 
                    'code': 404}), 404 

不是 所有 都可以由蓝图处理,但如果您要注册的只是错误处理程序,那么蓝图是一个很好的方法。

照常导入蓝图并将其注册到您的应用:

from yourmodule import common_errors 
app.register_blueprint(common_errors)