【已解决】Flask中如何使用已定义的Http状态码和错误码

想要在Flask去使用Http的错误码,

不想要直接写400,表示bad request

而想要试用别处已经定义好的http的状态码

搜:

Flask Bad Request

Application Errors — Flask Documentation (0.11)

-》

HTTP Exceptions — Werkzeug Documentation (0.11)

exception werkzeug.exceptions.HTTPException(description=None, response=None)

Baseclass for all HTTP exceptions. This exception can be called as WSGI application to render a default error page or you can catch the subclasses of it independently and render nicer error messages.

call(environ, start_response)

Call the exception as WSGI application.

Parameters:    

environ – the WSGI environment.

start_response – the response callable provided by the WSGI server.

get_response(environ=None)

Get a response object. If one was passed to the exception it’s returned directly.

Parameters:    environ – the optional environ for the request. This can be used to modify the response depending on how the request looked like.

Returns:    a Response object or a subclass thereof.

HTTP Exceptions — Werkzeug Documentation (0.11)

exception werkzeug.exceptions.BadRequest(description=None, response=None)

400 Bad Request

Raise if the browser sends something to the application the application or server cannot handle.

-》

还是没找到,具体如何使用。

Flask http status code

Custom Error Pages — Flask Documentation (0.11)

Implementing API Exceptions — Flask Documentation (0.11)

Flask http status code definition

List of HTTP status codes – Wikipedia

python – Flask – How to create custom abort() code? – Stack Overflow

python – Setting HTTP status code in Bottle? – Stack Overflow

去试试:

############################################################
# Flask
############################################################
from werkzeug.exceptions import *
    def put(self, userId, taskId):
        gLog.debug("BadRequest=%s", BadRequest)
        gLog.debug("BadRequest.code=%s", BadRequest.code)
        if userId == "":
            return genRespFailDict(code=BadRequest.code, message="user id can not empty")

好像是可以的:

<div–<——————————————————————————
DEBUG in Task [/root/RunningFast/staging/runningfast/resources/Task.py:209]:
BadRequest=<class ‘werkzeug.exceptions.BadRequest’>

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in Task [/root/RunningFast/staging/runningfast/resources/Task.py:210]:
BadRequest.code=400

【总结】

暂时可以去用:

from werkzeug.exceptions import *
gLog.debug("BadRequest.code=%s", BadRequest.code)

而使得不用直接写对应的400的值,显得更加直观。

对于其它异常的写法,详见:

HTTP Exceptions — Werkzeug Documentation (0.11)

和:

List of HTTP status codes – Wikipedia



发表评论

电子邮件地址不会被公开。 必填项已用*标注

无觅相关文章插件,快速提升流量