【问题标题】:Reusing boilerplate code across flask apps在烧瓶应用程序中重用样板代码
【发布时间】:2014-08-21 22:25:15
【问题描述】:

我的许多烧瓶应用程序都有一些错误处理调用。例如,我的 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

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

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

【问题讨论】:

标签: python error-handling flask code-reuse boilerplate


【解决方案1】:

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

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

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)

【讨论】:

  • 谢谢!很高兴再次见到你。如果我理解正确,此解决方案仅适用于错误处理,不适用于其他实用程序功能(例如 in your previous answer。蓝图会是解决方案吗?
  • @AdamMatan:该答案中的装饰器可以在任何地方重用。它们已经可重复使用。
  • 意思是我可以把它们放在一个蓝图中并在应用程序的其他地方注册它们?
  • @AdamMatan:蓝图可用于添加模板过滤器、模板全局变量、模板测试、请求挂钩、上下文处理器、url 默认值等。
  • @AdamMatan:您通常在在应用程序上注册的任何东西也可以在蓝图上注册,以仅应用于蓝图,或任何东西(名称中带有app_ 的任何东西都适用于所有路线,无处不在)。
猜你喜欢
  • 1970-01-01
  • 2015-02-12
  • 2022-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-27
  • 2016-10-27
  • 1970-01-01
相关资源
最近更新 更多