为某些域模式定义自定义错误处理程序?

如何解决为某些域模式定义自定义错误处理程序?

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

例如,认的错误页面一个带有类似“404: Not Found”的 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 响应。

解决方法

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

工作示例:

import json
from flask import Flask,abort,jsonify,Blueprint,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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?