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中计算三角函数之cos()方法的使用简介
May 15 Python
浅谈Python中的闭包
Jul 08 Python
定制FileField中的上传文件名称实例
Aug 23 Python
Python cookbook(数据结构与算法)同时对数据做转换和换算处理操作示例
Mar 23 Python
不管你的Python报什么错,用这个模块就能正常运行
Sep 14 Python
python抓取京东小米8手机配置信息
Nov 13 Python
解决py2exe打包后,总是多显示一个DOS黑色窗口的问题
Jun 21 Python
python识别文字(基于tesseract)代码实例
Aug 24 Python
python3 mmh3安装及使用方法
Oct 09 Python
Python动态强类型解释型语言原理解析
Mar 25 Python
python 通过文件夹导入包的操作
Jun 01 Python
Python中rapidjson参数校验实现
Jul 25 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
将酷狗krc歌词解析并转换为lrc歌词php源码
2014/06/20 PHP
PHP Yii框架之表单验证规则大全
2015/11/16 PHP
使用Huagepage和PGO来提升PHP7的执行性能
2015/11/30 PHP
Laravel框架运行出错提示RuntimeException No application encryption key has been specified.解决方法
2019/04/02 PHP
js计数器代码
2006/11/04 Javascript
纯JS实现根据CSS的class选择DOM
2014/03/22 Javascript
js+jquery常用知识点汇总
2015/03/03 Javascript
基于socket.io+express实现多房间聊天
2016/03/17 Javascript
jQuery事件用法详解
2016/10/06 Javascript
原生JS改变透明度实现轮播效果
2017/03/24 Javascript
Node.js实现文件上传的示例
2017/06/28 Javascript
vue mixins组件复用的几种方式(小结)
2017/09/06 Javascript
angularjs 页面自适应高度的方法
2018/01/17 Javascript
mpvue跳转页面及注意事项
2018/08/03 Javascript
微信小程序用户信息encryptedData详解
2018/08/24 Javascript
Vue学习之axios的使用方法实例分析
2020/01/06 Javascript
vue开发中遇到的问题总结
2020/04/07 Javascript
jQuery 淡入/淡出效果函数用法分析
2020/05/19 jQuery
微信小程序实现转盘抽奖
2020/09/21 Javascript
python正则表达式修复网站文章字体不统一的解决方法
2013/02/21 Python
Django中URLconf和include()的协同工作方法
2015/07/20 Python
Python3数据库操作包pymysql的操作方法
2018/07/16 Python
python如何写try语句
2020/07/14 Python
Bluebella美国官网:英国性感内衣品牌
2018/10/04 全球购物
Can a struct inherit from another struct? (结构体能继承结构体吗)
2016/09/25 面试题
会计专业毕业生推荐信
2013/11/05 职场文书
个人职业生涯规划书1500字
2013/12/31 职场文书
《中国梦我的梦》中学生演讲稿
2014/08/20 职场文书
个人工作作风整改措施思想汇报
2014/10/13 职场文书
入党积极分子党支部意见
2015/06/02 职场文书
2015年小学远程教育工作总结
2015/07/28 职场文书
幼儿园毕业典礼家长致辞
2015/07/29 职场文书
美容院员工规章制度
2015/08/05 职场文书
教学工作总结范文5篇
2019/08/19 职场文书
教你利用python实现企业微信发送消息
2021/05/23 Python
源码安装apache脚本部署过程详解
2022/09/23 Servers