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 相关文章推荐
Python中使用strip()方法删除字符串中空格的教程
May 20 Python
Python生成随机数组的方法小结
Apr 15 Python
Django后台获取前端post上传的文件方法
May 28 Python
Scrapy框架爬取西刺代理网免费高匿代理的实现代码
Feb 22 Python
Python虚拟环境的原理及使用详解
Jul 02 Python
Python Lambda函数使用总结详解
Dec 11 Python
python 使用cx-freeze打包程序的实现
Mar 14 Python
django模型动态修改参数,增加 filter 字段的方式
Mar 16 Python
jupyter修改文件名方式(TensorFlow)
Apr 21 Python
Python中常见的数制转换有哪些
May 27 Python
Python Matplotlib绘图基础知识代码解析
Aug 31 Python
Python爬虫入门案例之爬取去哪儿旅游景点攻略以及可视化分析
Oct 16 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
php+ajax导入大数据时产生的问题处理
2014/06/11 PHP
PHP 7安装调试工具Xdebug扩展的方法教程
2017/06/17 PHP
微信推送功能实现方式图文详解
2019/07/12 PHP
ExtJS的FieldSet的column列布局
2009/11/20 Javascript
Javascript中Eval函数的使用
2010/03/23 Javascript
extjs grid设置某列背景颜色和字体颜色的实现方法
2010/09/06 Javascript
JS实现div居中示例
2014/04/17 Javascript
angularjs中的e2e测试实例
2014/12/06 Javascript
javascript中createElement的两种创建方式
2015/05/14 Javascript
jQuery实现文本框输入同步的方法
2015/06/20 Javascript
Bootstrap3使用typeahead插件实现自动补全功能
2016/07/07 Javascript
微信小程序 wx:key详细介绍
2016/10/28 Javascript
浅谈JavaScript的自动垃圾收集机制
2016/12/15 Javascript
vue.js源代码core scedule.js学习笔记
2017/07/03 Javascript
JS实现的将html转为pdf功能【基于浏览器端插件jsPDF】
2018/02/06 Javascript
JS使用setInterval实现的简单计时器功能示例
2018/04/19 Javascript
element-ui组件table实现自定义筛选功能的示例代码
2019/03/15 Javascript
js实现贪吃蛇小游戏
2019/10/29 Javascript
实现一个Vue自定义指令懒加载的方法示例
2020/06/04 Javascript
python网络编程学习笔记(四):域名系统
2014/06/09 Python
Python开发中爬虫使用代理proxy抓取网页的方法示例
2017/09/26 Python
Python爬虫实战之12306抢票开源
2019/01/24 Python
对Python中小整数对象池和大整数对象池的使用详解
2019/07/09 Python
python卸载后再次安装遇到的问题解决
2019/07/10 Python
对pytorch的函数中的group参数的作用介绍
2020/02/18 Python
python实现数学模型(插值、拟合和微分方程)
2020/11/13 Python
实例讲解HTML5的meta标签的一些应用
2015/12/08 HTML / CSS
日本著名化妆品零售网站:Cosme Land
2019/03/01 全球购物
花店创业计划书范文
2014/02/07 职场文书
毕业典礼主持词大全
2014/03/26 职场文书
个人承诺书
2014/03/26 职场文书
《中国梦我的梦》中学生演讲稿
2014/08/20 职场文书
员工辞退通知书
2015/04/17 职场文书
工作证明格式范文
2015/06/15 职场文书
护士工作心得体会
2016/01/25 职场文书
Golang中interface{}转为数组的操作
2021/04/30 Golang