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获取apk文件URL地址实例
Nov 01 Python
Python 实现 贪吃蛇大作战 代码分享
Sep 07 Python
Python for循环中的陷阱详解
Jul 13 Python
python基于socket进行端口转发实现后门隐藏的示例
Jul 25 Python
Python中注释(多行注释和单行注释)的用法实例
Aug 28 Python
python、Matlab求定积分的实现
Nov 20 Python
python 初始化一个定长的数组实例
Dec 02 Python
Python栈的实现方法示例【列表、单链表】
Feb 22 Python
Python pathlib模块使用方法及实例解析
Oct 05 Python
python实现自动打卡的示例代码
Oct 10 Python
scrapy处理python爬虫调度详解
Nov 23 Python
对象析构函数__del__在Python中何时使用
Mar 22 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
thinkphp中的多表关联查询的实例详解
2017/10/12 PHP
PHP面向对象程序设计之多态性的应用示例
2018/12/19 PHP
用JQuery模仿淘宝的图片放大镜显示效果
2011/09/15 Javascript
JavaScript?Apple设备检测示例代码
2013/11/15 Javascript
JS使用ajax从xml文件动态获取数据显示的方法
2015/03/24 Javascript
谈谈javascript中使用连等赋值操作带来的问题
2015/11/26 Javascript
jQuery form插件之formDdata参数校验表单及验证后提交
2016/01/23 Javascript
JS工作中的小贴士之”闭包“与事件委托的”阻止冒泡“
2016/06/16 Javascript
jQuery+正则+文本框只能输入数字的实现方法
2016/10/07 Javascript
js判断文件格式及大小的简单实例(必看)
2016/10/11 Javascript
解决给dom元素绑定click等事件无效问题的方法
2017/02/17 Javascript
巧用weui.topTips验证数据的实例
2017/04/17 Javascript
JS实现div模块的截图并下载功能
2017/10/17 Javascript
vuejs实现折叠面板展开收缩动画效果
2018/09/06 Javascript
Vue中的methods、watch、computed的区别
2018/11/26 Javascript
iview tabs 顶部导航栏和模块切换栏的示例代码
2019/03/04 Javascript
vue treeselect获取当前选中项的label实例
2020/08/31 Javascript
[00:32]10月24、25日 辉夜杯外卡赛附加赛开赛!
2015/10/23 DOTA
python代码制作configure文件示例
2014/07/28 Python
python中遍历文件的3个方法
2014/09/02 Python
Django中使用group_by的方法
2015/05/26 Python
Python算法应用实战之栈详解
2017/02/04 Python
详解Python多线程Selenium跨浏览器测试
2017/04/01 Python
python实现装饰器、描述符
2018/02/28 Python
Matplotlib 生成不同大小的subplots实例
2018/05/25 Python
儿童学习python的一些小技巧
2018/05/27 Python
python opencv实现运动检测
2018/07/10 Python
Python中的枚举类型示例介绍
2019/01/09 Python
Django DRF路由与扩展功能的实现
2020/06/03 Python
详解python3 GUI刷屏器(附源码)
2021/02/18 Python
优秀毕业生自我鉴定
2014/01/19 职场文书
小学生获奖感言范文
2014/02/02 职场文书
财务部副经理岗位职责范本
2014/06/17 职场文书
领导班子四风问题个人对照检查材料
2014/10/04 职场文书
Python基础之常用库常用方法整理
2021/04/30 Python
Python 多线程处理任务实例
2021/11/07 Python