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'>}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2021-09-11 Linux学习31-如何查看 linux 系统是centos还是ubuntu,并查看系统版本号
2019-09-11 python测试开发django-rest-framework-59.restful接口开发