Flask之请求钩子的实现


Posted in Python onDecember 23, 2018

请求钩子

通过装饰器为一个模块添加请求钩子, 对当前模块的请求进行额外的处理. 比如权限验证.

说白了,就是在执行视图函数前后你可以进行一些处理,Flask使用装饰器为我们提供了注册通用函数的功能。

1、before_first_request:在处理第一个请求前执行

before_first_request

在对应用程序实例的第一个请求之前注册要运行的函数, 只会执行一次

#: A lists of functions that should be called at the beginning of the
  #: first request to this instance. To register a function here, use
  #: the :meth:`before_first_request` decorator.
  #:
  #: .. versionadded:: 0.8
  self.before_first_request_funcs = []

  @setupmethod
  def before_first_request(self, f):
    """Registers a function to be run before the first request to this
    instance of the application.

    .. versionadded:: 0.8
    """
    self.before_first_request_funcs.append(f)

将要运行的函数存放到before_first_request_funcs 属性中进行保存

2、before_request:在每次请求前执行

在每个请求之前注册一个要运行的函数, 每一次请求都会执行

#: A dictionary with lists of functions that should be called at the
  #: beginning of the request. The key of the dictionary is the name of
  #: the blueprint this function is active for, `None` for all requests.
  #: This can for example be used to open database connections or
  #: getting hold of the currently logged in user. To register a
  #: function here, use the :meth:`before_request` decorator.
  self.before_request_funcs = {} 

  @setupmethod
  def before_request(self, f):
    """Registers a function to run before each request."""
    self.before_request_funcs.setdefault(None, []).append(f)
    return f

将要运行的函数存放在字典中, None 为键的列表中存放的是整个应用的所有请求都要运行的函数.

3、after_request:每次请求之后调用,前提是没有未处理的异常抛出

在每个请求之后注册一个要运行的函数, 每次请求都会执行. 需要接收一个 Response 类的对象作为参数 并返回一个新的Response 对象 或者 直接返回接受到的Response 对象

#: A dictionary with lists of functions that should be called after
  #: each request. The key of the dictionary is the name of the blueprint
  #: this function is active for, `None` for all requests. This can for
  #: example be used to open database connections or getting hold of the
  #: currently logged in user. To register a function here, use the
  #: :meth:`after_request` decorator.
  self.after_request_funcs = {}

  @setupmethod
  def after_request(self, f):
    """Register a function to be run after each request. Your function
    must take one parameter, a :attr:`response_class` object and return
    a new response object or the same (see :meth:`process_response`).

    As of Flask 0.7 this function might not be executed at the end of the
    request in case an unhandled exception occurred.
    """
    self.after_request_funcs.setdefault(None, []).append(f)
    return f

4、teardown_request:每次请求之后调用,即使有未处理的异常抛出

注册一个函数在每个请求的末尾运行,不管是否有异常, 每次请求的最后都会执行.

#: A dictionary with lists of functions that are called after
  #: each request, even if an exception has occurred. The key of the
  #: dictionary is the name of the blueprint this function is active for,
  #: `None` for all requests. These functions are not allowed to modify
  #: the request, and their return values are ignored. If an exception
  #: occurred while processing the request, it gets passed to each
  #: teardown_request function. To register a function here, use the
  #: :meth:`teardown_request` decorator.
  #:
  #: .. versionadded:: 0.7
  self.teardown_request_funcs = {}

  @setupmethod
  def teardown_request(self, f):
    """Register a function to be run at the end of each request,
    regardless of whether there was an exception or not. These functions
    are executed when the request context is popped, even if not an
    actual request was performed.
    """
    self.teardown_request_funcs.setdefault(None, []).append(f)
    return f

将要运行的函数存放在字典中, None 为键的列表中存放的是整个应用的所有请求都要运行的函数.

from flask import Flask
app = Flask(__name__)

@app.before_first_request
def before_first_request():
  print('before_first_request')


@app.before_request
def before_request():
  print('before_request')


@app.after_request
def after_request(resp):
  print('after_request')
  return resp


@app.teardown_request
def teardown_request(e):
  print('teardown_request')


@app.route("/")
def view_fn():
  return "view_fn"
  
if __name__ == "__main__":
  app.run()

第一次请求:

页面输出:view_fn
控制台输出: before_first_request
            before_request
            after_request
            teardown_request

第二次请求:

页面输出:view_fn
控制台输出: before_request
            after_request
            teardown_request

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Windows8下安装Python的BeautifulSoup
Jan 22 Python
对于Python异常处理慎用“except:pass”建议
Apr 02 Python
python搭建服务器实现两个Android客户端间收发消息
Apr 12 Python
python进程和线程用法知识点总结
May 28 Python
Python+selenium点击网页上指定坐标的实例
Jul 05 Python
使用Python代码实现Linux中的ls遍历目录命令的实例代码
Sep 07 Python
OpenCV里的imshow()和Matplotlib.pyplot的imshow()的实现
Nov 25 Python
Python基于requests库爬取网站信息
Mar 02 Python
python实现从ftp服务器下载文件
Mar 03 Python
基于matplotlib中ion()和ioff()的使用详解
Jun 16 Python
写好Python代码的几条重要技巧
May 21 Python
http通过StreamingHttpResponse完成连续的数据传输长链接方式
Feb 12 Python
python爬虫获取新浪新闻教学
Dec 23 #Python
Python爬虫文件下载图文教程
Dec 23 #Python
python爬虫获取百度首页内容教学
Dec 23 #Python
Python爬虫设置代理IP(图文)
Dec 23 #Python
celery4+django2定时任务的实现代码
Dec 23 #Python
python3使用pandas获取股票数据的方法
Dec 22 #Python
Python实现将通信达.day文件读取为DataFrame
Dec 22 #Python
You might like
点评山进PR-D3L三波段收音机
2021/03/02 无线电
php分页示例代码
2007/03/19 PHP
PHP无敌近乎加密方式!
2010/07/17 PHP
php中使用$_REQUEST需要注意的一个问题
2013/05/02 PHP
php cURL和Rolling cURL并发方式比较
2013/10/30 PHP
让CodeIgniter数据库缓存自动过期的处理的方法
2014/06/12 PHP
用php守护另一个php进程的例子
2015/02/13 PHP
PHP基于SimpleXML生成和解析xml的方法示例
2017/07/17 PHP
PHP PDOStatement::execute讲解
2019/01/31 PHP
php实现商城购物车的思路和源码分析
2020/07/23 PHP
使用js声明数组,对象在jsp页面中(获得ajax得到json数据)
2013/11/05 Javascript
js判断undefined类型,undefined,null, 的区别详细解析
2013/12/16 Javascript
BOOTSTRAP时间控件显示在模态框下面的bug修复
2015/02/05 Javascript
jQuery与getJson结合的用法实例
2015/08/07 Javascript
js实现有过渡渐变效果的图片轮播相册(兼容IE,ff)
2016/01/19 Javascript
开启BootStrap学习之旅
2016/05/04 Javascript
微信小程序 wx:key详细介绍
2016/10/28 Javascript
如何提高Dom访问速度
2017/01/05 Javascript
JavaScript基本语法_动力节点Java学院整理
2017/06/26 Javascript
[01:03:56]Mineski vs TNC 2018国际邀请赛淘汰赛BO1 8.21
2018/08/22 DOTA
[02:04]完美世界城市挑战赛秋季赛报名开始 谁是solo路人王?
2019/10/10 DOTA
python操作摄像头截图实现远程监控的例子
2014/03/25 Python
Django中实现点击图片链接强制直接下载的方法
2015/05/14 Python
Python抓取淘宝下拉框关键词的方法
2015/07/08 Python
python3的输入方式及多组输入方法
2018/10/17 Python
Python第三方库face_recognition在windows上的安装过程
2019/05/03 Python
Django多数据库的实现过程详解
2019/08/01 Python
Django Admin设置应用程序及模型顺序方法详解
2020/04/01 Python
python实现二分查找算法
2020/09/18 Python
皇家道尔顿官网:Royal Doulton
2017/12/06 全球购物
Office DEPOT法国官网:欧迪办公用品采购
2018/01/03 全球购物
什么是Deployment descriptors;都有什么类型的部署描述符
2015/07/28 面试题
入股合作协议书
2014/10/12 职场文书
学校国庆节活动总结
2015/03/23 职场文书
Python基础详解之描述符
2021/04/28 Python
MySQL数据库事务的四大特性
2022/04/20 MySQL