Flask 学习-68. abort() 退出请求

前言

使用 abort() 可以 更早退出请求,并返回错误代码

abort() 函数

使用abort函数可以立即终止视图函数的执行,并可以返回特定的信息

abort(404)  # 404 Not Found
abort(Response('Hello World'))

源码介绍

def abort(
    status: t.Union[int, "Response"], *args: t.Any, **kwargs: t.Any
) -> "te.NoReturn":
    """Raises an :py:exc:`HTTPException` for the given status code or WSGI
    application.

    If a status code is given, it will be looked up in the list of
    exceptions and will raise that exception.  If passed a WSGI application,
    it will wrap it in a proxy WSGI exception and raise that::

       abort(404)  # 404 Not Found
       abort(Response('Hello World'))

    """
    _aborter(status, *args, **kwargs)

使用示例

from flask import Flask, request, g, abort, Response
app = Flask(__name__)


@app.route("/demo", methods=["GET"])
def demo():
    if not request.args.get('user'):
        abort(400)  # 400 bad request
    else:
        res = Response('hello world')
        return abort(res)

注意,状态码要出现在Flask定义的异常号列表(the list of exceptions)中,否则会引发内部服务器错误,比如,传递206,307就会报错

LookupError
LookupError: no exception for 307

exceptions 异常列表

异常列表定义在werkzeug.exceptions.default_exceptions中。
使用pprint可以查看全部状态码和对应的类

import pprint
import werkzeug
pprint.pprint(werkzeug.exceptions.default_exceptions)

运行结果

{400: <class 'werkzeug.exceptions.BadRequest'>,
 401: <class 'werkzeug.exceptions.Unauthorized'>,
 403: <class 'werkzeug.exceptions.Forbidden'>,
 404: <class 'werkzeug.exceptions.NotFound'>,
 405: <class 'werkzeug.exceptions.MethodNotAllowed'>,
 406: <class 'werkzeug.exceptions.NotAcceptable'>,
 408: <class 'werkzeug.exceptions.RequestTimeout'>,
 409: <class 'werkzeug.exceptions.Conflict'>,
 410: <class 'werkzeug.exceptions.Gone'>,
 411: <class 'werkzeug.exceptions.LengthRequired'>,
 412: <class 'werkzeug.exceptions.PreconditionFailed'>,
 413: <class 'werkzeug.exceptions.RequestEntityTooLarge'>,
 414: <class 'werkzeug.exceptions.RequestURITooLarge'>,
 415: <class 'werkzeug.exceptions.UnsupportedMediaType'>,
 416: <class 'werkzeug.exceptions.RequestedRangeNotSatisfiable'>,
 417: <class 'werkzeug.exceptions.ExpectationFailed'>,
 418: <class 'werkzeug.exceptions.ImATeapot'>,
 422: <class 'werkzeug.exceptions.UnprocessableEntity'>,
 423: <class 'werkzeug.exceptions.Locked'>,
 424: <class 'werkzeug.exceptions.FailedDependency'>,
 428: <class 'werkzeug.exceptions.PreconditionRequired'>,
 429: <class 'werkzeug.exceptions.TooManyRequests'>,
 431: <class 'werkzeug.exceptions.RequestHeaderFieldsTooLarge'>,
 451: <class 'werkzeug.exceptions.UnavailableForLegalReasons'>,
 500: <class 'werkzeug.exceptions.InternalServerError'>,
 501: <class 'werkzeug.exceptions.NotImplemented'>,
 502: <class 'werkzeug.exceptions.BadGateway'>,
 503: <class 'werkzeug.exceptions.ServiceUnavailable'>,
 504: <class 'werkzeug.exceptions.GatewayTimeout'>,
 505: <class 'werkzeug.exceptions.HTTPVersionNotSupported'>}
posted @ 2022-09-11 16:23  上海-悠悠  阅读(275)  评论(0编辑  收藏  举报