Der*_*rek 22 werkzeug flask flask-restful
使用方法很容易使用flask-restful传播错误消息到客户端abort(),例如
abort(500, message="Fatal error: Pizza the Hutt was found dead earlier today
in the back seat of his stretched limo. Evidently, the notorious gangster
became locked in his car and ate himself to death.")
Run Code Online (Sandbox Code Playgroud)
这将生成以下json输出
{
"message": "Fatal error: Pizza the Hutt was found dead earlier today
in the back seat of his stretched limo. Evidently, the notorious gangster
became locked in his car and ate himself to death.",
"status": 500
}
Run Code Online (Sandbox Code Playgroud)
有没有办法用其他成员自定义json输出?例如:
{
"sub_code": 42,
"action": "redirect:#/Outer/Space"
"message": "You idiots! These are not them! You've captured their stunt doubles!",
"status": 500
}
Run Code Online (Sandbox Code Playgroud)
Mig*_*uel 33
人们倾向于过度使用abort(),而实际上生成自己的错误非常简单.您可以编写一个可以轻松生成自定义错误的函数,这里的函数与您的JSON匹配:
def make_error(status_code, sub_code, message, action):
response = jsonify({
'status': status_code,
'sub_code': sub_code,
'message': message,
'action': action
})
response.status_code = status_code
return response
Run Code Online (Sandbox Code Playgroud)
然后而不是调用abort()这样做:
@route('/')
def my_view_function():
# ...
if need_to_return_error:
return make_error(500, 42, 'You idiots!...', 'redirect...')
# ...
Run Code Online (Sandbox Code Playgroud)
小智 24
我没有50个评论@dappiu的声誉,所以我只需要写一个新的答案,但它确实与"Flask-RESTful设法提供一种更清晰的方法来处理错误"有关,因为这里记录很少
这是一个糟糕的文件,花了我一段时间来弄清楚如何使用它.关键是你的自定义异常必须从flask_restful导入HTTPException继承.请注意,您不能使用Python异常.
from flask_restful import HTTPException
class UserAlreadyExistsError(HTTPException):
pass
custom_errors = {
'UserAlreadyExistsError': {
'message': "A user with that username already exists.",
'status': 409,
}
}
api = Api(app, errors=custom_errors)
Run Code Online (Sandbox Code Playgroud)
Flask-RESTful团队已经很好地完成了自定义异常处理,但是文档破坏了工作量.
@Miguel的代码是大多数时候应该使用的代码:没有异常,只需在请求处理程序的分支中返回响应即可。但是,如果您确实需要引发异常的异常中止机制(例如,这在过滤方法中可能有用),请注意flask.abort接受一个Response对象(请检查此要点):
from flask import abort, make_response, jsonify
abort(make_response(jsonify(message="Message goes here"), 400))
Run Code Online (Sandbox Code Playgroud)
我不同意@Miguel 关于abort(). 除非您使用 Flask 来构建 HTTP 应用程序以外的东西(使用请求/响应范例),否则我相信您应该尽可能多地使用它HTTPExceptions(请参阅werkzeug.exceptions模块)。这也意味着使用中止机制(这只是这些异常的捷径)。相反,如果您选择在视图中显式构建并返回您自己的错误,则会导致您进入一种模式,您需要使用一系列 if/else/return 检查值,这通常是不必要的。请记住,您的函数很可能在请求/响应管道的上下文中运行。在做出决定之前不必一路返回视图,只需在失败点中止请求并完成它。该框架完全理解这种模式,并具有应对这种模式的偶然性。并且您仍然可以在需要时捕获异常(也许用额外的消息补充它,或者挽救请求)。
因此,类似于@Miguel 的但保持预期的中止机制:
def json_abort(status_code, data=None):
response = jsonify(data or {'error': 'There was an error'})
response.status_code = status_code
abort(response)
# then in app during a request
def check_unique_username(username):
if UserModel.by__username(username):
json_abort(409, {'error': 'The username is taken'})
def fetch_user(user_id):
try:
return UserModel.get(user_id)
except UserModel.NotFound:
json_abort(404, {'error': 'User not found'})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14333 次 |
| 最近记录: |