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中分数的相关使用教程
Mar 30 Python
详细介绍Ruby中的正则表达式
Apr 10 Python
python实现爬虫统计学校BBS男女比例(一)
Dec 31 Python
Django中间件实现拦截器的方法
Jun 01 Python
pandas求两个表格不相交的集合方法
Dec 08 Python
python实现图书借阅系统
Feb 20 Python
Python生成验证码、计算具体日期是一年中的第几天实例代码详解
Oct 16 Python
python误差棒图errorbar()函数实例解析
Feb 11 Python
python3.6环境下安装freetype库和基本使用方法(推荐)
May 10 Python
python中的列表和元组区别分析
Dec 30 Python
python中的被动信息搜集
Apr 29 Python
关于python中模块和重载的问题
Nov 02 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缩放图片(根据宽高的等比例缩放)实例介绍
2013/06/09 PHP
php和html的区别点详细总结
2019/09/24 PHP
WordPress 照片lightbox效果的运用几点
2009/06/22 Javascript
使用JQUERY Tabs插件宿主IFRAMES
2010/01/01 Javascript
基于JQuery实现的类似购物商城的购物车
2011/12/06 Javascript
window.event.keyCode兼容IE和Firefox实现js代码
2013/05/30 Javascript
jQuery基于BootStrap样式实现无限极地区联动
2016/08/26 Javascript
Vuex和前端缓存的整合策略详解
2017/05/09 Javascript
JS仿QQ好友列表展开、收缩功能(第一篇)
2017/07/07 Javascript
cocos creator Touch事件应用(触控选择多个子节点的实例)
2017/09/10 Javascript
JS解决IOS中拍照图片预览旋转90度BUG的问题
2017/09/13 Javascript
[05:29]2014DOTA2国际邀请赛 赛后专访:LGDNewbee顺利过关
2014/07/13 DOTA
[02:00]DAC2018主宣传片——龙征四海,剑问东方
2018/03/20 DOTA
[10:18]2018DOTA2国际邀请赛寻真——Fnatic能否笑到最后?
2018/08/14 DOTA
[58:25]VP vs RNG 2019国际邀请赛小组赛 BO2 第一场 8.15
2019/08/17 DOTA
python实现将html表格转换成CSV文件的方法
2015/06/28 Python
pandas DataFrame数据转为list的方法
2018/04/11 Python
python: 自动安装缺失库文件的方法
2018/10/22 Python
Pycharm配置远程调试的方法步骤
2018/12/17 Python
对Python中class和instance以及self的用法详解
2019/06/26 Python
python使用socket实现的传输demo示例【基于TCP协议】
2019/09/24 Python
pygame编写音乐播放器的实现代码示例
2019/11/19 Python
Pytorch提取模型特征向量保存至csv的例子
2020/01/03 Python
使用Python爬虫库requests发送表单数据和JSON数据
2020/01/25 Python
Python sys模块常用方法解析
2020/02/20 Python
Python库skimage绘制二值图像代码实例
2020/04/10 Python
Python基于numpy模块实现回归预测
2020/05/14 Python
CSS3实现鼠标悬停显示扩展内容
2016/08/24 HTML / CSS
John Hardy官方网站:手工设计首饰的奢侈品牌
2017/07/05 全球购物
Ruby如何创建一个线程
2013/03/10 面试题
模具毕业生推荐信
2014/02/15 职场文书
校庆筹备方案
2014/03/30 职场文书
病人写给医生的感谢信
2015/01/23 职场文书
世界文化遗产导游词
2019/08/07 职场文书
浅谈redis五大数据结构和使用场景
2021/04/12 Redis
给numpy.array增加维度的超简单方法
2021/06/02 Python