[英]Flask-restful not-found handling for blueprint
在關於自定義錯誤處理程序的 Flask-restful 文檔中,它說:
Flask-RESTful 將在 Flask-RESTful 路由上發生任何 400 或 500 錯誤時調用 handle_error() function,而不會影響其他路由。 您可能希望您的應用在出現 404 Not Found 錯誤時返回帶有正確媒體類型的錯誤消息; 在這種情況下,使用 Api 構造函數的 catch_all_404s 參數。
我對帶有藍圖的 API 的簡化設置:
from flask import Blueprint
from flask_restful import Api
from .resources.tool import ToolDetail, Tools
api_bp = Blueprint('api', __name__, subdomain='<hostname>', url_prefix='/api')
api = Api(api_bp, catch_all_404s=True)
api.add_resource(Tools, '/tools', '/tools/<int:page>', '/tools/<int:page>/<int:per_page>')
api.add_resource(ToolDetail, '/tool/<int:id>')
使用catch_all_404s=True
任何 404 都會產生如下響應:
{
"message": "The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again."
}
也適用於其他藍圖的請求! 我希望catch_all_404s=True
僅對定義的藍圖產生影響。
從 handle_error() function 上方的代碼片段中刪除catch_all_404s=True
永遠不會被調用。 也不適用於帶有/api
路徑的請求。
所以我的問題是:如何讓 flask-restful 捕獲藍圖中的所有 404,但不在藍圖中(即不在其他藍圖中)。
編輯:正如下面的評論所指出的,這種不限於藍圖的 catch_all 行為是由 Flask 本身的限制引起的。 仍然存在的問題:使用catch_all_404s=False
時,404 永遠不會被 flask-restful 捕獲,即使在路由中也是如此,例如http://somehost.domain.com/api/tools/x被應用程序的錯誤處理程序捕獲,而不是flask-restful 的錯誤處理程序。
flask-restful 中的 Api class 處理錯誤。 如果您希望在應用程序級別處理錯誤,請讓錯誤處理程序使用 handle_error 方法在自定義 class 中重新引發錯誤。 您還可以使用相同的方法處理特定於藍圖的自定義錯誤。 自定義類(ExtendApi)擴展基礎 class Api
class ExtendApi(Api):
"""This class overrides 'handle_error' method of 'Api' class ,
to extend global exception handing functionality of 'flask-restful'.
"""
def handle_error(self, e):
# reraise the error so that it is handled in the app level error handlers
# Add custom handlers below if required
if getattr(e, "code"):
if e.code == 404:
return {"message": "My custom message"}, 404
raise e
使用來自 flask-restful 的自定義 class 而不是 Api
my_blueprint = Blueprint("my_blueprint", __name__)
blueprint_api = ExtendApi(my_blueprint)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.