在烧瓶应用程序中重用样板代码

Ada*_*tan 1 python error-handling code-reuse boilerplate 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
Run Code Online (Sandbox Code Playgroud)

由于我有大量的样板代码,我想将它放在一个公共文件中,并从一个地方继承或导入我的烧瓶应用程序.

是否可以从其他模块继承或导入烧瓶样板代码?

Mar*_*ers 6

当然有,但你需要参数化注册.

而不是使用装饰器,将注册移动到一个函数:

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)
Run Code Online (Sandbox Code Playgroud)

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

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

要支持蓝图,您还需要等待Flask的下一个版本(包括此提交),或者直接使用装饰器功能:

app_or_blueprint.errorhandler(404)(page_not_found)
Run Code Online (Sandbox Code Playgroud)

对于很多这些任务,您也可以使用蓝图,前提是您使用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
Run Code Online (Sandbox Code Playgroud)

并非所有内容都可以由蓝图处理,但如果您注册的只是错误处理程序,那么蓝图就是一种很好的方法.

像往常一样导入蓝图并将其注册到您的应用:

from yourmodule import common_errors
app.register_blueprint(common_errors)
Run Code Online (Sandbox Code Playgroud)