为 json 返回 api 自定义烧瓶错误处理程序

san*_*rma 1 python error-handling flask custom-error-handling

我有一个 Flask 应用程序,它有两种类型的路线:

(1). 网站路由,如 /home、/user/、/news_feed

(2). json 返回移动应用程序的 api,如 /api/user、/api/weather 等。

我正在通过flask提供的@app.errorhandler装饰器使用自定义错误页面来处理常见错误,例如404和500 -对于我的网站

@app_instance.errorhandler(404)
def page_note_found_error(err):
  return render_template("err_404.html"), 404

@app_instance.errorhandler(500)
def internal_server_error(err):
  db_instance.session.rollback()
  return render_template("err_500.html"), 500
Run Code Online (Sandbox Code Playgroud)

如果说我通过移动 api 收到 500 错误,我不希望我的移动 api 返回这些错误页面。

有没有办法绕过或自定义某些路由(api)的错误处理程序,以便它返回 json 响应而不是我的自定义错误页面

mha*_*wke 6

您可以深入研究请求的详细信息以确定 URL 路径。如果路径/api/带有前缀,则您可以将其视为 API 请求并返回 JSON 响应。

from flask import request, jsonify

API_PATH_PREFIX = '/api/'

@app_instance.errorhandler(404)
def page_not_found_error(error):
    if request.path.startswith(API_PATH_PREFIX):
        return jsonify({'error': True, 'msg': 'API endpoint {!r} does not exist on this server'.format(request.path)}), error.code
    return render_template('err_{}.html'.format(error.code)), error.code
Run Code Online (Sandbox Code Playgroud)

这并不理想。我认为您可能已经能够使用 Flask 蓝图来处理这个问题,但是蓝图特定的错误处理程序不适用于 404,而是调用了应用程序级别的处理程序。