Request的中断和ErrorHandler实例解析
作者:阏男秀 时间:2021-11-25 18:42:04
概述
在view函数中,如果需要中断request,可以使用abort(500)或者直接raise exception。当然我们还需要返回一个出错信息给前端,所以需要定制一下ErrorHandler。一般只需要两个个handler即可,一个是404错误,一个是500一类的服务器端错误。当然也可以自定义错误。
代码清单
下面是一份示例代码,main是一个蓝本或者app,发生404错误或500错误,会返回一个Json对象给请求段。
from flask import jsonify
from . import main
@main.errorhandler(404)
def error_404(error):
"""这个handler可以catch住所有abort(404)以及找不到对应router的处理请求"""
response = dict(status=0, message="404 Not Found")
return jsonify(response), 404
@main.errorhandler(Exception)
def error_500(error):
"""这个handler可以catch住所有的abort(500)和raise exeception."""
response = dict(status=0, message="500 Error")
return jsonify(response), 400
class MyError(Exception):
"""自定义错误类"""
pass
@main.errorhandler(MyError)
def MyErrorHandle(error):
response = dict(status=0, message="400 Error")
return jsonify(response), 400
蓝本的错误处理
在蓝本中编写错误处理程序有点不同,如果使用errorhandler修饰器,那么只有蓝本中的错误才会触发。如果想注册全局的错误处理程序,要用app_errorhandler。
例如:
from . import auth
@auth.app_errorhandler(404)
def error_404(error):
response = dict(status=0, message="404 Not Found")
return jsonify(response), 404
来源:http://blog.csdn.net/yannanxiu/article/details/52137781
标签:python,request,中断
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python+tifffile之tiff文件读写方式
2022-03-16 13:17:41
Python 实现简单的电话本功能
2021-11-16 09:47:58
迎来2009年CSS裸奔节(CSS Naked Day )
2009-04-24 12:41:00
![](https://img.aspxhome.com/file/UploadPic/20094/24/qqqqqqqqq-36s.gif)
Pytorch转tflite方式
2023-08-10 03:47:29
Android分包MultiDex策略详解
2021-11-14 13:28:42
基于Django的ModelForm组件(详解)
2022-03-07 18:21:04
使用CSS3和RGBa创建超酷的按钮
2009-06-02 12:41:00
Python中的流程控制详解
2023-07-22 20:31:54
python基于property()函数定义属性
2022-11-01 04:55:14
python matplotlib自定义colorbar颜色条及内置色条详解
2023-04-03 16:50:34
![](https://img.aspxhome.com/file/2023/6/79436_0s.png)
用js实现放大镜效果
2023-09-19 18:29:29
![](https://img.aspxhome.com/file/2023/0/56200_0s.jpg)
Django项目中model的数据处理以及页面交互方法
2022-12-26 20:12:25
![](https://img.aspxhome.com/file/2023/5/101655_0s.jpg)
Yahoo!网站性能最佳体验的34条黄金守则——JavaScript和CSS
2008-05-29 13:34:00
python查找与排序算法详解(示图+代码)
2023-08-05 13:27:26
![](https://img.aspxhome.com/file/2023/1/77631_0s.png)
在Lighttpd服务器中运行Django应用的方法
2021-08-05 20:19:50
Linux CentOS7下安装python3 的方法
2023-09-17 03:40:08
Python实现base64编码
2023-10-01 02:34:50
Python 安装setuptools和pip工具操作方法(必看)
2023-11-06 11:46:07
![](https://img.aspxhome.com/file/2023/1/65091_0s.png)
页面制作人员的修练之道
2023-11-10 23:52:18
python中get和post有什么区别
2022-04-17 16:45:15