在前缀为特定内容的路由上注册自定义错误处理程序

时间:2014-06-25 20:15:14

标签: python flask

我的应用有一个应用工厂模式,如下所示:

def create_app(environment):
  # ...

  from root import root
  from charts import user_charts, download_charts
  app.register_blueprint(root)
  app.register_blueprint(user_charts, url_prefix='/charts/user')
  app.register_blueprint(download_charts, url_prefix='/charts/downloads')

  return app

Root有一个特殊的错误处理程序,因为它是根蓝图

@root.app_errorhandler(404)
def not_found(e):
  return render_template('404.html'), 404

如果他们试图访问根本不存在的页面,这是有好处的。但是,在前缀为/chart的URL上,前端向json对象的后端发出请求。我希望在所有这些路线上都有一个统一的处理程序,而不是明确地在每个蓝图上注册它,因为大约有10个。我不想这样做。相反,我想要这样的东西:

@(all routes prefixed with '/chart').errorhandler(404)
def chart_not_found(e):
  return jsonify({
    'error': e,
    'message': e.get_description()
  })

然而,问题是有很多蓝图以' / chart'为前缀。

有没有办法在多个共享前缀的网址上注册相同的错误处理程序,而不是在每个蓝图上重复它?

1 个答案:

答案 0 :(得分:1)

只需在初始时注册:

def chart_not_found(e):
  return jsonify({
    'error': e,
    'message': e.get_description()
  })

def create_app(environment):
  # ...

  from root import root
  from charts import user_charts, download_charts

  user_charts.error_handler(404)(chart_not_found)
  download_charts.error_handler(404)(chart_not_found)
  # ... snip remaining ...

您甚至可以创建一个列出所有图表蓝图的模块级变量,然后使用for

# charts/__init__.py
chart_handlers = (('/charts/user', user_charts),
                  ('/charts/downloads', download_charts))

# Then in your init setup
from charts import chart_handlers

for prefix, chart_handler in chart_handlers:
    chart_handler.error_handler(404)(chart_not_found)
    app.register_blueprint(chart_handler, prefix)