如何解决为某些域模式定义自定义错误处理程序?
我正在使用 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 举报,一经查实,本站将立刻删除。