【问题标题】:Defining custom error handlers for certain domain patterns?为某些域模式定义自定义错误处理程序?
【发布时间】:2021-10-06 19:07:51
【问题描述】:

我正在使用 Flask,我想知道是否可以根据域模式自定义错误页面。

例如,默认错误页面是带有“404:未找到”之类的 HTML 响应。我正在为子域api.localhost:5000 设置一个类似 REST 的 API。我想做的是以某种方式告诉 Flask,如果您看到诸如 api.localhost:5000/* 之类的域并且您收到 404,则发回 jsonified 响应,否则继续发回 HTML 响应。

这是一个简单的例子:

from flask import abort, jsonify, Blueprint
api = Blueprint("api", __name__)

@api.route("/bad/route", subdomain="api")
def api_base():
    """Purposefly define a bad route and send back jsonified error response."""
    # Forcefully calling `abort` will generate a jsonified response
    abort(404)
    # However, if I didn't anticipate a bad path and didn't call `abort`, a
    # default HTML 404 page is returned, which is defined in the `error`
    # blueprint located elsewhere in the application.

@api.errorhandler(404)
def resource_not_found(e):
    return jsonify(error=str(e)), 404

如果我提出请求:

http://api.localhost:5000/bad/route

我会得到一个不错的 json 响应,否则像 http://api.localhost:5000/another/bad/route 这样的东西会返回一个 404 HTML 响应。

【问题讨论】:

    标签: python python-3.x flask uwsgi flask-restful


    【解决方案1】:

    使用您自己的 process_response 创建一个自定义烧瓶类

    工作示例:

    import json
    from flask import Flask, abort, jsonify, Blueprint, jsonify, make_response
    
    api = Blueprint("api", __name__)
    
    @api.route("/good")
    def good_route():
        return app.make_response("Hello World")
    
    @api.route("/bad/route")
    def api_base():
        """Purposefly define a bad route and send back jsonified error response."""
        # Forcefully calling `abort` will generate a jsonified response
        abort(404)
        # However, if I didn't anticipate a bad path and didn't call `abort`, a
        # default HTML 404 page is returned, which is defined in the `error`
        # blueprint located elsewhere in the application.
    
    @api.errorhandler(404)
    def resource_not_found(e):
        return jsonify(error=str(e)), 404
    
    
    class MyFlask(Flask):
        def process_response(self, response):
            #Every response will be processed here first
            if response.status_code == 404:
                # send a json response
                return make_response(jsonify({"error": "Route Not found"}), 404)
            return response
    
    app = MyFlask("api")
    app.register_blueprint(api)
    

    测试它:

    (venv) bhakta@blr:~/dev/flask$ curl -D headers -X GET http://api.localhost:5000/good
    Hello World(venv) bhakta@blr:~/dev/flask$
    (venv) bhakta@blr:~/dev/flask$
    (venv) bhakta@blr:~/dev/flask$
    (venv) bhakta@blr:~/dev/flask$ cat headers
    HTTP/1.0 200 OK
    Content-Type: text/html; charset=utf-8
    Content-Length: 11
    Server: Werkzeug/0.15.0 Python/3.6.8
    Date: Sun, 01 Aug 2021 10:35:38 GMT
    
    (venv) bhakta@blr:~/dev/flask$
    (venv) bhakta@blr:~/dev/flask$
    (venv) bhakta@blr:~/dev/flask$
    
    (venv) bhakta@blr:~/dev/flask$ curl -D headers -X GET http://api.localhost:5000/bad
    {"error":"Route Not found"}
    (venv) bhakta@blr:~/dev/flask$
    (venv) bhakta@blr:~/dev/flask$
    (venv) bhakta@blr:~/dev/flask$ cat headers
    HTTP/1.0 404 NOT FOUND
    Content-Type: application/json
    Content-Length: 28
    Server: Werkzeug/0.15.0 Python/3.6.8
    Date: Sun, 01 Aug 2021 10:35:43 GMT
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-18
      • 1970-01-01
      • 2018-04-29
      • 2011-06-01
      • 1970-01-01
      • 2013-01-04
      • 2011-04-21
      • 1970-01-01
      相关资源
      最近更新 更多