最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

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

Flask crifan 5937浏览 0评论

想要在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

转载请注明:在路上 » 【已解决】Flask中如何使用已定义的Http状态码和错误码

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
89 queries in 0.213 seconds, using 22.21MB memory