【发布时间】: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