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

Python 在前缀为特定内容的路由上注册自定义错误处理程序,python,flask,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_blu

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

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有一个特定于应用程序的errorhandler,因为它是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()
  })
然而,问题是有许多以“/charts”为前缀的蓝图


有没有一种方法可以跨共享前缀的多个URL注册相同的错误处理程序,而不是在每个蓝图上重复它?

只需在初始时间注册即可:

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 ...
您甚至可以创建一个模块级变量,列出所有图表蓝图,然后对使用

# 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)

此外,还值得一看一些对大型应用程序有用的其他模式(免责声明,我是作者)。