Sanic框架异常处理与中间件操作实例分析


Posted in Python onJuly 16, 2018

本文实例讲述了Sanic框架异常处理与中间件操作。分享给大家供大家参考,具体如下:

简介

Sanic是一个类似Flask的Python 3.5+ Web服务器,它的写入速度非常快。除了Flask之外,Sanic还支持异步请求处理程序。这意味着你可以使用Python 3.5中新的闪亮的异步/等待语法,使你的代码非阻塞和快速。

前言Sanic最低支持Python 3.5,如果需要学习Sanic,请先下载版本不低于3.5的Python包

异常

异常可以从请求处理程序中抛出,并由Sanic自动处理。异常将消息作为第一个参数,并且还可以将状态码传回HTTP响应中。

抛出异常:手动产生异常的方式,有过Python基础的都知道,可以使用raise来产生一个异常:

from sanic.exceptions import ServerError
from sanic.response import text
@app.route("/get_exception")
async def get_exception(request):
  raise ServerError("it is error",status_code=500)

你也可以使用abort:

from sanic.exceptions import abort
from sanic.response import text
@app.route("/get_exception")
async def get_exception(request):
  abort(402)
  text("ok")

处理异常:有时我们需要对一些特殊异常做特殊处理,此时我们可以用到@app.exception装饰器,然后在定义一个异常函数来进行处理。异常装饰器处理函数必须以一个RequestException对象作为参数:

from sanic.response import text
from sanic.exceptions import NotFound
@app.exception(NotFound)
async def not_found_exception(request,exception):
  return text("not found=>{}".format(request.url))

中间件

中间件是服务器在请求之前或之后执行的功能,他们可以用来修改修改用户定义处理函数的请求或相应。Sanic提供两种类型的中间件:请求和响应。两者都是使用@app.middleware装饰器声明,两个装饰器分别需要传入一个代表其类型的参数:requestresponse,下面举一个简单的栗子:

from sanic.response import text
@app.route("/get_info")
async def get_info(request):
  print(request.url)
  return text("it is ok!")
@app.middleware("request")
async def get_request_middleware(request):
  print("请求中间件")
@app.middleware("response")
async def get_response_middleware(request,response):
  print("响应中间件")

当我们访问/get_info请求时,打印结果将会是这样的:

请求中间件

http://localhost:5000/get_info

响应中间件

值得注意的是,如果是响应中间的处理函数,除了需要传递一个request对象参数,还需要传递一个response对象参数。从结果可以看出,request中间件是在接收到请求时立马触发的,而response中间件是在接收到响应时立马触发的。针对这两者的特性,我们可以进行一些特殊的操作,来达到我们的目的:

@app.middleware("request")
async def get_request_middleware(request):
  request.args.update({"name":"laozhang"})
@app.middleware("response")
async def get_response_middleware(request,response):
  response.headers["name"] = "laozhang"

将所有的请求的args添加一条name=laozhang,并且在响应头中添加name=laozhang

监听器

如果需要在服务器启动/关闭的时候,执行一些特殊的代码,则可以使用以下监听器:

  • before_server_start:在服务器启动之前执行
  • after_server_start:在服务器启动之后执行
  • before_server_stop:在服务器关闭之前执行
  • after_server_stop:在服务器关闭之后执行

举个栗子:

@app.listener("before_server_start")
async def before_server_start(request,loop):
  print("before_server_start")
@app.listener("after_server_start")
async def after_server_start(request,loop):
  print("after_server_start")
@app.listener("before_server_stop")
async def before_server_stop(request,loop):
  print("before_server_stop")
@app.listener("after_server_stop")
async def after_server_stop(request,loop):
  print("after_server_stop")

现在先启动服务,而后关闭,发现执行的顺序将会是这样:

before_server_start
after_server_start
before_server_stop
after_server_stop

更多关于Python相关内容可查看本站专题:《Python入门与进阶经典教程》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
Python内建数据结构详解
Feb 03 Python
Python中matplotlib中文乱码解决办法
May 12 Python
Python实现OpenCV的安装与使用示例
Mar 30 Python
解决python 文本过滤和清理问题
Aug 28 Python
Pytorch保存模型用于测试和用于继续训练的区别详解
Jan 10 Python
python实现五子棋游戏(pygame版)
Jan 19 Python
python如何通过pyqt5实现进度条
Jan 20 Python
Python基于read(size)方法读取超大文件
Mar 12 Python
150行Python代码实现带界面的数独游戏
Apr 04 Python
基于Python的Jenkins的二次开发操作
May 12 Python
使用keras实现BiLSTM+CNN+CRF文字标记NER
Jun 29 Python
利用Python实时获取steam特惠游戏数据
Jun 25 Python
对pycharm代码整体左移和右移缩进快捷键的介绍
Jul 16 #Python
对Python3.6 IDLE常用快捷键介绍
Jul 16 #Python
Sanic框架请求与响应实例分析
Jul 16 #Python
解决Python 中英文混输格式对齐的问题
Jul 16 #Python
Django实战之用户认证(用户登录与注销)
Jul 16 #Python
Python3数据库操作包pymysql的操作方法
Jul 16 #Python
django缓存配置的几种方法详解
Jul 16 #Python
You might like
php控制文件下载速度的方法
2015/03/24 PHP
php字符串函数学习之substr()
2015/03/27 PHP
php使用CutyCapt实现网页截图保存的方法
2016/10/03 PHP
基于thinkphp6.0的success、error实现方法
2019/11/05 PHP
js局部刷新页面时间具体实现
2013/07/04 Javascript
使用js修改客户端注册表的方法
2013/08/09 Javascript
js 判断js函数、变量是否存在的简单示例代码
2014/03/04 Javascript
Javascript中的关键字和保留字整理
2014/10/16 Javascript
jquery实现鼠标拖拽滑动效果来选择数字的方法
2015/05/04 Javascript
jQuery 生成svg矢量二维码
2016/08/09 Javascript
深入理解JavaScript中的并行处理
2016/09/22 Javascript
javascript解析ajax返回的xml和json格式数据实例详解
2017/01/05 Javascript
使用vue.js实现checkbox的全选和多个的删除功能
2017/02/17 Javascript
Angularjs2不同组件间的通信实例代码
2017/05/06 Javascript
在微信小程序中使用图表的方法示例
2019/04/25 Javascript
Python编写百度贴吧的简单爬虫
2015/04/02 Python
python比较2个xml内容的方法
2015/05/11 Python
python数字图像处理之高级滤波代码详解
2017/11/23 Python
python定时检测无响应进程并重启的实例代码
2019/04/22 Python
Python学习笔记之lambda表达式用法详解
2019/08/08 Python
python 多进程队列数据处理详解
2019/12/23 Python
Python如何把多个PDF文件合并代码实例
2020/02/13 Python
python中 _、__、__xx__()区别及使用场景
2020/06/30 Python
Python 防止死锁的方法
2020/07/29 Python
详解Python openpyxl库的基本应用
2021/02/26 Python
SQL Server 2000数据库的文件有哪些,分别进行描述。
2015/11/09 面试题
垃圾回收的优点和原理
2014/05/16 面试题
质量月活动策划方案
2014/03/10 职场文书
房屋授权委托书范本
2014/10/07 职场文书
承诺书模板大全
2015/05/04 职场文书
教师年度考核自我评鉴
2015/08/11 职场文书
大学生就业指导课心得体会
2016/01/15 职场文书
Python中OpenCV实现简单车牌字符切割
2021/06/11 Python
Django REST framework 限流功能的使用
2021/06/24 Python
解决pycharm下载库时出现Failed to install package的问题
2021/09/04 Python
能用CSS实现的就不要麻烦JavaScript了
2021/10/05 HTML / CSS