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网络编程之TCP通信实例和socketserver框架使用例子
Apr 25 Python
Python+Pika+RabbitMQ环境部署及实现工作队列的实例教程
Jun 29 Python
深入浅析ImageMagick命令执行漏洞
Oct 11 Python
Python numpy 点数组去重的实例
Apr 18 Python
python实现log日志的示例代码
Apr 28 Python
python一键去抖音视频水印工具
Sep 14 Python
对python中的 os.mkdir和os.mkdirs详解
Oct 16 Python
python随机在一张图像上截取任意大小图片的方法
Jan 24 Python
详解爬虫被封的问题
Apr 23 Python
浅谈python输出列表元素的所有排列形式
Feb 26 Python
python openpyxl模块的使用详解
Feb 25 Python
详解python的内存分配机制
May 10 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
使用Linux五年积累的一些经验技巧
2013/06/20 PHP
PHP中使用Memache作为进程锁的操作类分享
2015/03/30 PHP
laravel 解决Eloquent ORM的save方法无法插入数据的问题
2019/10/21 PHP
jquery 查找新建元素代码
2010/07/06 Javascript
关于setInterval、setTimeout在jQuery中的使用注意事项
2011/09/28 Javascript
jquery制作 随机弹跳的小球特效
2015/02/01 Javascript
jquery背景跟随鼠标滑动导航
2015/11/20 Javascript
在vue-cli脚手架中配置一个vue-router前端路由
2017/07/03 Javascript
js定时器实现倒计时效果
2017/11/05 Javascript
微信小程序基于本地缓存实现点赞功能的方法
2017/12/18 Javascript
解决vue脚手架项目打包后路由视图不显示的问题
2018/09/20 Javascript
vue.js中导出Excel表格的案例分析
2019/06/11 Javascript
jQuery表单选择器用法详解
2019/08/22 jQuery
在vue项目实现一个ctrl+f的搜索功能
2020/02/28 Javascript
浅谈JS for循环中使用break和continue的区别
2020/07/21 Javascript
Python环境变量设置方法
2016/08/28 Python
详解python发送各类邮件的主要方法
2016/12/22 Python
django实现前后台交互实例
2017/08/07 Python
TensorFlow saver指定变量的存取
2018/03/10 Python
带你认识Django
2019/01/15 Python
对PyQt5中的菜单栏和工具栏实例详解
2019/06/20 Python
pytorch如何冻结某层参数的实现
2020/01/10 Python
python numpy--数组的组合和分割实例
2020/02/24 Python
Python TKinter如何自动关闭主窗口
2020/02/26 Python
Nginx+Uwsgi+Django 项目部署到服务器的思路详解
2020/05/08 Python
Django用户登录与注册系统的实现示例
2020/06/03 Python
10分钟理解CSS3 Grid布局
2018/12/20 HTML / CSS
中医药大学市场营销专业自荐信
2013/09/29 职场文书
汽车维修工岗位职责
2014/02/12 职场文书
普通话演讲稿
2014/09/03 职场文书
一份没有按时交货失信于客户的检讨书
2014/09/19 职场文书
2014年社区个人工作总结
2014/12/02 职场文书
兴趣班停课通知
2015/04/24 职场文书
铁人纪念馆观后感
2015/06/16 职场文书
提升Nginx性能的一些建议
2021/03/31 Servers
Promise静态四兄弟实现示例详解
2022/07/07 Javascript