使用Flask-Restful引发自定义错误 [英] Raising A Custom Error with Flask-Restful
问题描述
全部,我正在尝试使用Flask-Restful引发自定义错误,并遵循
这似乎是标准的409错误,没有任何自定义;从文档中,我希望收到自定义错误消息-具有该用户名的用户已存在." 我认为我缺少有关错误本身引发的信息.我应该以任何方式使用字典键吗?尽管我尝试了一下,但查看Flask-Restful的源代码并没有帮助. 要使用 Flask-RESTful 为标准 HTTP状态代码定义一条消息,您必须重新定义一个 Werkzeug 提供的HTTP异常中, Flask 基于. >
以下是您忽略问题的示例,该示例覆盖了 因此,每次调用 但是,通过使用此方法,在任何地方您都将使用 因此,我建议您每次要提供自定义消息时,只需使用 Flask-RESTful 的 All, I'm trying to raise a custom error using Flask-Restful, following the docs. For testing purposes, I've defined and registered the errors dictionary exactly link in the docs: However, when I want to raise the custom error using (e.g.) {
"message": "Conflict",
"status": 409
} This seems like the standard 409 error, nothing custom; from the docs, I would expect the custom error message- "A user with that username already exists." I think I'm missing something regarding the raising of the error itself. Should I use the dictionary key in any way? Reviewing the Flask-Restful source code didn't help, though I tried. To define a message for a standard HTTP status code with Flask-RESTful, you must redefine one of the HTTP exceptions provided by Werkzeug, on which Flask is based. Following your question, here is an example to override the Hence, every time you will call However, by using this method, in any place you will abort with a So, I advise you to simply use the Generally speaking, extending Flask-RESTful by defining custom error messages is useful when you raise custom exceptions (with 这篇关于使用Flask-Restful引发自定义错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!errors = {
'Conflict': {
'message': "A user with that username already exists.",
'status': 409,
},
}
app = Flask(__name__)
api = flask_restful.Api(app, errors=errors)
abort(409)
时,这将返回正确的媒体类型和定义的消息的表示形式.409
状态代码中止,这将返回有关用户名已经存在的用户的消息.在处理除用户以外的其他资源的视图中调用abort(409)
时,这不太可能实现.abort
方法:from flask.ext.restful import abort
abort(409, description="A user with that username already exists.")
api = flask_restful.Api(app, errors=errors)
.abort(409)
within the resource module, firebug reports:
Conflict
exception:errors = {
'Conflict': {
'message': "A user with that username already exists.",
'status': 409,
},
}
app = Flask(__name__)
api = flask_restful.Api(app, errors=errors)
abort(409)
, this will return a representation in the right mediatype, and with the defined message.409
status code, this will return a message about a user with a username that already exists. This is unlikely what you want when you call abort(409)
in a view that deals with other resources than users.abort
method of Flask-RESTful as follows, every time you want to provide a custom message:from flask.ext.restful import abort
abort(409, description="A user with that username already exists.")
raise()
, not abort()
) which are not in the HTTP exceptions provided by Werkzeug.