当前位置:网站首页>【flask入门系列】异常处理
【flask入门系列】异常处理
2022-07-17 06:37:00 【馆主阿牛】
个人简介
- 作者简介:大家好,我是阿牛,全栈领域新星创作者。
- 博主的个人网站:阿牛的博客小屋
- 支持我:点赞+收藏️+留言
- 系列专栏:flask框架快速入门
- 格言:要成为光,因为有怕黑的人!

前言
今天简单介绍一哈flask中对于异常处理的办法,算是属于表较冷门的知识点了,因为我们用python的知识来实现这些需求处理,但我们还是要学习一下,因为他可以帮我们集中处理异常,而不用在每个视图中进行异常处理。
HTTP异常主动抛出
- abort方法
抛出一个给定状态代码的HTTPException或者指定响应,例如想要用一个页面未找到异常来终止请求,你可以调用abort(404) - 参数
code-HTTP的错误状态码。只能抛出http协议的错误代码。
#导入Flask类和request对象
from flask import Flask,request,abort
app = Flask(__name__)
@app.route('/articles')
def get_articles():
channel_id = request.args.get('channel_id')
if channel_id is None:
abort(400) #400 Bad Request
return 'you want get articles of channel {}'.format(channel_id)
# Flask应用程序的run方法启动web服务器
if __name__ == '__main__':
app.run(port=8000)

捕获错误
- errorhandler装饰器
注册一个错误处理程序,当程序抛出指定错误状态码的时候,就会调用该装饰器所装饰的方法。 - 参数
code_or_exception - HTTP的错误状态码或指定异常。 - 例如统一处理状态码为500的错误给用户有好的提示。
@app.errorhandler(500)
def internal_server_err(e):
return "服务器搬家了"
- 捕获指定异常
@app.errorhandler(ZeroDivisionError)
def zero_division_err(e):
return "除数不能为零"
例:
#导入Flask类
from flask import Flask
app = Flask(__name__)
@app.errorhandler(ZeroDivisionError)
def zero_division_err(e):
# 这里的e是异常对象
print(e)
return "除数不能为零"
@app.route("/")
def index():
s = 1/0
return s
# Flask应用程序的run方法启动web服务器
if __name__ == '__main__':
app.run(port=8000)


由图可以看出,遇到异常会立即停止执行当前视图,而去执行对应的异常处理视图。
结语
如果你觉得博主写的还不错的话,可以关注一下当前专栏,博主会更完这个系列的哦!也欢迎订阅博主的其他好的专栏。
边栏推荐
- DP动态规划企业级模板分析(数字三角,上升序列,背包,状态机,压缩DP)
- the max_ iter was reached which means the coef_ did not converge “the coef_ did not converge“
- First experience of openvino machine learning
- Use of mongodb
- Redis 跳跃表实现原理 & 时间复杂度分析
- What if the user information in the website app database is leaked and tampered with
- redis事务
- 神经网络和自动控制的联系
- Understand LSTM and Gru
- The connection between neural network and automatic control
猜你喜欢
![[MySQL] lock mechanism: detailed explanation of lock classification, table lock, row lock and page lock in InnoDB engine](/img/7e/ddf05e76da26e9b2d1fd1519703571.png)
[MySQL] lock mechanism: detailed explanation of lock classification, table lock, row lock and page lock in InnoDB engine

1669. Merge two linked lists (merge of two linked lists)

Visit Beijing Zoo in dog days

Redis jump table implementation principle & time complexity analysis

Object detection and bounding box

YOLOV5-打标签建立自己的数据集

Discussion on risc-v Technology

redis事务

通过Dao投票STI的销毁,SeekTiger真正做到由社区驱动

Pytoch notes (1)
随机推荐
Random forest of machine learning
Modify scroll bar style
Visit Beijing Zoo in dog days
@How can conditionalonmissingbean cover beans in third-party components
微信OAuth2.0 登录流程以及安全性分析
[C language] user defined type details: structure, enumeration, union
Use of mongodb
Regular expression extraction of matching content
Standard Version (release and changelog Automation)
Is it necessary to buy pension insurance? What are the pension products suitable for the elderly?
STM32F103C8T6硬件IIC控制4针0.96寸OLED显示屏
The website vulnerability repair service provider analyzes the ultra vires caused by controllable parameters
VMware Cloud Director 10.4 发布 (含下载) - 云计算调配和管理平台
If a number in C language is exactly equal to the sum of its factors, this number is called "perfect". For example, 6=1 + 2 + 3 programming
Pytoch notes (2)
Xilinx ultrascale+ MPSoC (zu9eg/zu15eg) high performance PCIe data preprocessing board
[C# 变量常量关键字]- C# 中的变量常量以及关键字
美联储降息,为何长期利好数字货币市场? 2020-03-05
【C语言】自定义类型详解:结构体、枚举、联合
Redis源码分析之双索引机制