您当前的位置: 首页 >  flask
  • 0浏览

    0关注

    214博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Flask(5):Flask的装饰器函数

不愿透露姓名の网友 发布时间:2020-08-03 22:32:43 ,浏览量:0

文章目录
  • 一、常用装饰器函数
    • 1.视图函数执行前的中间件函数。
    • 2.视图函数执行后的中间件函数。
    • 3.多个装饰器函数
    • 4.特别注意
    • 5.写一个登录装饰器
  • 二、其他装饰器函数
    • 1.自定义错误页面
    • 2.前端直接调用后端函数的装饰器
    • 3.相当于filter的装饰器
    • 4.第一次来请求操作的装饰器

一、常用装饰器函数 1.视图函数执行前的中间件函数。

想在执行视图函数前,先执行一个装饰器的函数,类似Django的process_request中间件函数一样

from flask import Flask

app = Flask(__name__, template_folder='templates')

@app.before_request
def A():
    print('执行函数前先执行我')


@app.route('/index/')
def index():
    print('我是视图函数')
    return ''

在这里插入图片描述

2.视图函数执行后的中间件函数。

想在执行完视图函数,再执行一个装饰器的函数,类似Django的process_response中间件函数一样

from flask import Flask

app = Flask(__name__, template_folder='templates')

@app.before_request
def A():
    print('执行函数前先执行我')

@app.after_request
def B(response):
    print('执行函数完再执行我')
    return response

@app.route('/index/')
def index():
    print('我是视图函数')
    return ''


if __name__ == '__main__':
    app.run(debug=True)

在这里插入图片描述

@app.after_request的函数必须要接受视图函数传回的响应,并且return它,否则会报错 在这里插入图片描述

3.多个装饰器函数

现在有多个装饰器函数,查看执行顺序

from flask import Flask

app = Flask(__name__, template_folder='templates')

@app.before_request
def A1():
    print('执行函数前先执行我1')

@app.before_request
def A2():
    print('执行函数前先执行我2')

@app.after_request
def B1(response):
    print('执行函数完再执行我1')
    return response

@app.after_request
def B2(response):
    print('执行函数完再执行我2')
    return response

@app.route('/index/')
def index():
    print('我是视图函数')
    return ''


if __name__ == '__main__':
    app.run(debug=True)

在这里插入图片描述

原理:

before_request=[A1,A2] 会按顺序执行列表里的装饰器函数
after_request=[B1,B2] 会先将列表执行reverse操作,再执行装饰器函数
4.特别注意

如果在befor_request的函数中如果return返回值,那么不会再执行视图函数,会直接把响应交个after_requesr函数。

5.写一个登录装饰器
@app.before_request
def check_login():
    # 如果当前不在login页面,则不需要验证
    if request.path=='/login':
        return None
    # 如果不是login页面,需要验证
    user=session.get('user')
    if user != 'zs':
        return redirect('/login')
二、其他装饰器函数 1.自定义错误页面
@app.error_handlers(404)
def error_404(arg):
     '''自定义错误页面,根据状态码定制'''
     return "404错误啦"
2.前端直接调用后端函数的装饰器
@app.template_global()
def xx(a1,a2):
    return a1+a2
'''
这个装饰器的作用就是,可以在前端直接通过{{ xx(1,2)}}来调用后端的这个函数。
'''
3.相当于filter的装饰器
@app.template_filter()
def db(a1,a2,a3):
    return a1+a2+a3
'''
效果和django的Filter相似,前端渲染的时候需要注意写法
{{ 1|db(2,3)}} 1是第一个参数,后面是2,3参数。
'''
4.第一次来请求操作的装饰器
@app.before_first_request
def first(*args,**kwargs):
    pass
'''
只有第一次请求时候才执行的函数装饰器
'''
关注
打赏
1657102503
查看更多评论
立即登录/注册

微信扫码登录

0.0374s