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 20 Python
Python编程中实现迭代器的一些技巧小结
Jun 21 Python
20招让你的Python飞起来!
Sep 27 Python
详解Python装饰器由浅入深
Dec 09 Python
pytorch构建网络模型的4种方法
Apr 13 Python
Tensorflow实现卷积神经网络的详细代码
May 24 Python
python 利用pandas将arff文件转csv文件的方法
Feb 12 Python
GitHub 热门:Python 算法大全,Star 超过 2 万
Apr 29 Python
python笔记之mean()函数实现求取均值的功能代码
Jul 05 Python
基于tensorflow指定GPU运行及GPU资源分配的几种方式小结
Feb 03 Python
基于matplotlib中ion()和ioff()的使用详解
Jun 16 Python
用pushplus+python监控亚马逊到货动态推送微信
Jan 29 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数组中删除元素的实现代码
2012/06/22 PHP
php中session过期时间设置及session回收机制介绍
2014/05/05 PHP
Yii入门教程之Yii安装及hello world
2014/11/25 PHP
PHP函数shuffle()取数组若干个随机元素的方法分析
2016/04/02 PHP
PHP简单获取及判断提交来源的方法
2016/04/22 PHP
对于Laravel 5.5核心架构的深入理解
2018/02/22 PHP
PHP如何实现阿里云短信sdk灵活应用在项目中的方法
2019/06/14 PHP
mouse_on_title.js
2006/08/25 Javascript
ArrayList类(增强版)
2007/04/04 Javascript
javascript 混合的构造函数和原型方式,动态原型方式
2009/12/07 Javascript
javascript删除字符串最后一个字符
2014/01/14 Javascript
Javascript基础知识(三)BOM,DOM总结
2014/09/29 Javascript
jQuery层级选择器用法分析
2015/02/10 Javascript
jquery实现仿新浪微博带动画效果弹出层代码(可关闭、可拖动)
2015/10/12 Javascript
Vue 组件间的样式冲突污染
2017/08/31 Javascript
webpack里使用jquery.mCustomScrollbar插件的方法
2018/05/30 jQuery
react-native android状态栏的实现
2018/06/15 Javascript
浏览器事件循环与vue nextTicket的实现
2019/04/16 Javascript
微信小程序Flex布局用法深入浅出分析
2019/04/25 Javascript
vue中的过滤器及其时间格式化问题
2020/04/09 Javascript
原生js实现日期选择插件
2020/05/21 Javascript
jquery绑定事件 bind和on的用法与区别分析
2020/05/22 jQuery
Python利用正则表达式匹配并截取指定子串及去重的方法
2015/07/30 Python
Python的Flask框架中的Jinja2模板引擎学习教程
2016/06/30 Python
使用Python将Mysql的查询数据导出到文件的方法
2019/02/25 Python
Python实现的爬取百度贴吧图片功能完整示例
2019/05/10 Python
Python全栈之列表数据类型详解
2019/10/01 Python
Python常用扩展插件使用教程解析
2020/11/02 Python
丝绸和人造花卉、植物和树木:Nearly Natural
2018/11/28 全球购物
医药个人求职信范文
2014/01/29 职场文书
2014年小学元旦活动方案
2014/02/12 职场文书
党员2014两会学习心得体会
2014/03/17 职场文书
金融系应届毕业生求职信
2014/05/26 职场文书
推普周活动总结
2014/08/28 职场文书
超市店长竞聘书
2015/09/15 职场文书
成功的商业计划书这样写才最靠谱
2019/07/12 职场文书