Jah*_*yst 6 python flask flask-restful
我想为Flask-restful API定义自定义错误处理。
在文档中建议的方法在这里是要做到以下几点:
errors = {
'UserAlreadyExistsError': {
'message': "A user with that username already exists.",
'status': 409,
},
'ResourceDoesNotExist': {
'message': "A resource with that ID no longer exists.",
'status': 410,
'extra': "Any extra information you want.",
},
}
app = Flask(__name__)
api = flask_restful.Api(app, errors=errors)
Run Code Online (Sandbox Code Playgroud)
现在,我发现此格式非常吸引人,但是当发生某些异常时,我需要指定更多参数。例如,遇到时ResourceDoesNotExist,我要指定id不存在的内容。
目前,我正在执行以下操作:
app = Flask(__name__)
api = flask_restful.Api(app)
class APIException(Exception):
def __init__(self, code, message):
self._code = code
self._message = message
@property
def code(self):
return self._code
@property
def message(self):
return self._message
def __str__(self):
return self.__class__.__name__ + ': ' + self.message
class ResourceDoesNotExist(APIException):
"""Custom exception when resource is not found."""
def __init__(self, model_name, id):
message = 'Resource {} {} not found'.format(model_name.title(), id)
super(ResourceNotFound, self).__init__(404, message)
class MyResource(Resource):
def get(self, id):
try:
model = MyModel.get(id)
if not model:
raise ResourceNotFound(MyModel.__name__, id)
except APIException as e:
abort(e.code, str(e))
Run Code Online (Sandbox Code Playgroud)
当使用不存在的ID调用时,MyResource将返回以下JSON:
{'message': 'ResourceDoesNotExist: Resource MyModel 5 not found'}
Run Code Online (Sandbox Code Playgroud)
这工作正常,但我想使用Flask-restful错误处理。
小智 7
我没有将错误字典附加到 Api,而是覆盖 Api 类的 handle_error 方法来处理我的应用程序的异常。
# File: app.py
# ------------
from flask import Blueprint, jsonify
from flask_restful import Api
from werkzeug.http import HTTP_STATUS_CODES
from werkzeug.exceptions import HTTPException
from view import SomeView
class ExtendedAPI(Api):
"""This class overrides 'handle_error' method of 'Api' class ,
to extend global exception handing functionality of 'flask-restful'.
"""
def handle_error(self, err):
"""It helps preventing writing unnecessary
try/except block though out the application
"""
print(err) # log every exception raised in the application
# Handle HTTPExceptions
if isinstance(err, HTTPException):
return jsonify({
'message': getattr(
err, 'description', HTTP_STATUS_CODES.get(err.code, '')
)
}), err.code
# If msg attribute is not set,
# consider it as Python core exception and
# hide sensitive error info from end user
if not getattr(err, 'message', None):
return jsonify({
'message': 'Server has encountered some error'
}), 500
# Handle application specific custom exceptions
return jsonify(**err.kwargs), err.http_status_code
api_bp = Blueprint('api', __name__)
api = ExtendedAPI(api_bp)
# Routes
api.add_resource(SomeView, '/some_list')
Run Code Online (Sandbox Code Playgroud)
自定义异常可以保存在单独的文件中,例如:
# File: errors.py
# ---------------
class Error(Exception):
"""Base class for other exceptions"""
def __init__(self, http_status_code:int, *args, **kwargs):
# If the key `msg` is provided, provide the msg string
# to Exception class in order to display
# the msg while raising the exception
self.http_status_code = http_status_code
self.kwargs = kwargs
msg = kwargs.get('msg', kwargs.get('message'))
if msg:
args = (msg,)
super().__init__(args)
self.args = list(args)
for key in kwargs.keys():
setattr(self, key, kwargs[key])
class ValidationError(Error):
"""Should be raised in case of custom validations"""
Run Code Online (Sandbox Code Playgroud)
并且在视图中可以引发异常,例如:
# File: view.py
# -------------
from flask_restful import Resource
from errors import ValidationError as VE
class SomeView(Resource):
def get(self):
raise VE(
400, # Http Status code
msg='some error message', code=SomeCode
)
Run Code Online (Sandbox Code Playgroud)
与视图一样,实际上可以从应用程序中的任何文件引发异常,这些文件将由 ExtendedAPI handle_error 方法处理。
根据文档
Flask-RESTful将在Flask-RESTful路由上发生的任何400或500错误上调用handle_error()函数,并且不理会其他路由。
您可以利用它来实现所需的功能。唯一的缺点是必须创建自定义Api。
class CustomApi(flask_restful.Api):
def handle_error(self, e):
flask_restful.abort(e.code, str(e))
Run Code Online (Sandbox Code Playgroud)
如果保留定义的异常,则当发生异常时,您将获得与
class MyResource(Resource):
def get(self, id):
try:
model = MyModel.get(id)
if not model:
raise ResourceNotFound(MyModel.__name__, id)
except APIException as e:
abort(e.code, str(e))
Run Code Online (Sandbox Code Playgroud)
小智 5
我已经使用蓝图来处理flask-restful,我发现在这个问题上提供的解决方案@billmccord 和@cedmt不适用于这种情况,因为蓝图没有handle_exception和handle_user_exception功能。
我的解决方法是,提高功能handle_error的Api,如果“异常”的“错误处理程序”已被注册,只是提出来,在应用程序注册了“错误处理程序”会处理该异常,或异常将被传递到“flask-restful”控制的“自定义错误处理程序”。
class ImprovedApi(Api):
def handle_error(self, e):
for val in current_app.error_handler_spec.values():
for handler in val.values():
registered_error_handlers = list(filter(lambda x: isinstance(e, x), handler.keys()))
if len(registered_error_handlers) > 0:
raise e
return super().handle_error(e)
api_entry = ImprovedApi(api_entry_bp)
Run Code Online (Sandbox Code Playgroud)
顺便说一句,似乎flask-restful已被弃用......
| 归档时间: |
|
| 查看次数: |
10206 次 |
| 最近记录: |