使用瓶怎么实现一个请求钩子

  介绍

这篇文章给大家介绍使用瓶怎么实现一个请求钩子,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

<强> 1,before_first_request:在处理第一个请求前执行

before_first_request

在对应用程序实例的第一个请求之前注册要运行的函数,只会执行一次

,, #:, A  lists  of  functions  that  should  be  nbsp; at 从而beginning  of    ,,#:first  request 用却;能够实例只用register  a  function 在这里,使用   ,,#:,:甲:“before_first_request”装饰。   #才能:   ,,#:…,versionadded:: 0.8   时间=self.before_first_request_funcs 才能;[]      @setupmethod才能   def 才能before_first_request(自我,,f):   ,,,“““Registers  a  function 用be  run  before 从而first  request 用这个   ,,,instance  of 从而应用程序。      ,,,. .,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  nbsp; at    ,,#:beginning  of 从而请求只,key  of 从而dictionary  is 从而name    #:才能,从而blueprint 却;能够function  is  active ,,‘没有’,for  all 请求。   #:才能,却;能够还要for  example  be  used 用open  database  connections 或   ,,#:getting 于of 从而currently  logged 用户只;用register 拷贝   ,,#:function 在这里,,use 从而:甲:“before_request”装饰。   self.before_request_funcs 才能=,{},      @setupmethod才能   def 才能before_request(自我,,f):   ,,,“““Registers  a  function 用run  before  each 请求!”““   ,,,self.before_request_funcs.setdefault(没有,,[]).append (f)   ,,,return  f

将要运行的函数存放在字典中,没有为键的列表中存放的是整个应用的所有请求都要运行的函数。

<强> 3,after_request:每次请求之后调用,前提是没有未处理的异常抛出

在每个请求之后注册一个要运行的函数,每次请求都会执行。需要接收一个响应类的对象作为参数并返回一个新的反应对象或者直接返回接受到的响应对象

,, #:, A  dictionary  with  lists  of  functions  that  should  be  nbsp;之后   ,,#:each 请求只,key  of 从而dictionary  is 从而name  of 从而蓝图   #:才能,却;能够function  is  active ,,‘没有’,for  all 请求只却;能够还要   ,,#:example  be  used 用open  database  connections 或是getting 于of    ,,#:currently  logged 用户只拷贝用register  a  function 在这里,use    ,,#::甲:“after_request”装饰。   self.after_request_funcs 才能=,{}      @setupmethod才能   def 才能after_request(自我,,f):   ,,,“““Register  a  function 用be  run  after  each 请求只Your 函数   ,,,must  take  one 参数,,a : attr:“response_class”, object 以及回报   ,,,a  new  response  object 看,趁机same (阅读:甲:“process_response”)。      ,,,As  of  Flask  0.7,却;能够function  might  not  be  executed  at 从而最终获得of    ,,,request 拷贝case  an  unhandled  exception 发生。   ,,,,,,   ,,,self.after_request_funcs.setdefault(没有,,[]).append (f)   ,,,return  f

<强> 4,teardown_request:每次请求之后调用,即使有未处理的异常抛出

注册一个函数在每个请求的末尾运行,不管是否有异常,每次请求的最后都会执行。

,, #:, A  dictionary  with  lists  of  functions  that 断开连接;nbsp;之后
  ,,#:each 请求,,even  if  an  exception  has 只发生,key  of 
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null

使用瓶怎么实现一个请求钩子