ric*_*hmb 46 python http http-error flask
使用python flask服务器,我希望能够使用abort命令抛出http错误响应,并在正文中使用自定义响应字符串和自定义消息
@app.errorhandler(400)
def custom400(error):
response = jsonify({'message': error.message})
response.status_code = 404
response.status = 'error.Bad Request'
return response
abort(400,'{"message":"custom error message to appear in body"}')
Run Code Online (Sandbox Code Playgroud)
但是error.message变量是一个空字符串.我似乎无法找到有关如何使用自定义错误处理程序访问中止函数的第二个变量的文档
Sea*_*ira 69
如果你看,flask/__init__.py你会看到abort实际上是从中导入的werkzeug.exceptions.查看Aborter该类,我们可以看到,当使用数字代码调用时,将HTTPException查找特定子类并使用提供给Aborter实例的所有参数进行调用.观察HTTPException,特别注意第85-89行,我们可以看到传递给的第二个参数HTTPException.__init__存储在description属性中,正如@dirn指出的那样.
您可以从description属性访问消息:
@app.errorhandler(400)
def custom400(error):
response = jsonify({'message': error.description['message']})
# etc.
abort(400, {'message': 'custom error message to appear in body'})
Run Code Online (Sandbox Code Playgroud)
或者只是简单地传递描述:
@app.errorhandler(400)
def custom400(error):
response = jsonify({'message': error.description})
# etc.
abort(400, 'custom error message to appear in body')
Run Code Online (Sandbox Code Playgroud)
Mig*_*uel 61
人们abort()过分依赖.事实是,有更好的方法来处理错误.
例如,您可以编写此辅助函数:
def bad_request(message):
response = jsonify({'message': message})
response.status_code = 400
return response
Run Code Online (Sandbox Code Playgroud)
然后从您的视图函数中,您可以返回错误:
@app.route('/')
def index():
if error_condition:
return bad_request('message that appears in body')
Run Code Online (Sandbox Code Playgroud)
如果在无法返回响应的位置调用堆栈中发生错误,则可以使用自定义异常.例如:
class BadRequestError(ValueError):
pass
@app.errorhandler(BadRequestError)
def bad_request_handler(error):
return bad_request(str(error))
Run Code Online (Sandbox Code Playgroud)
然后在需要发出错误的函数中,您只需引发异常:
def some_function():
if error_condition:
raise BadRequestError('message that appears in the body')
Run Code Online (Sandbox Code Playgroud)
我希望这有帮助.
Vas*_*cal 20
我只是这样做:
abort(400, description="Required parameter is missing")
Run Code Online (Sandbox Code Playgroud)
flask.abort 也接受 flask.Response
abort(make_response(jsonify(message="Error message"), 400))
Run Code Online (Sandbox Code Playgroud)