Python Flask 特殊装饰器,执行路由前和执行路由后执行的装饰器

发布时间 2024-01-11 18:11:55作者: 悟透

前言全局说明

Python Flask 特殊装饰器,执行路由前和执行路由后执行的装饰器


一、安装flask模块

官方源:

pip3 install flask==2.3.2

国内源:

pip3 install flask==2.3.2 -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com

以上二选一,哪个安装快用哪个
flask 安装时间 2023-11

更多国内源: https://www.cnblogs.com/wutou/p/17949398


二、引用模块

from flask import Flask

三、启动服务

https://www.cnblogs.com/wutou/p/17949220


四、特殊装饰器,在路由前和后执行的装饰器

html 不用多看,这次主要看命令行特殊装饰器执行前后的提示。
特殊装饰器用在,访问网页时,请求路由前先执行的函数,比如登录验证

4.1.2文件名:index.py
from flask import Flask, render_template, request

app=Flask(__name__)

@app.before_request
def bef():
    print('before_request')

@app.after_request
def aft(i):
    print('after_request')
    return i

@app.route('/')
def index():
    print('index')
    if request.method == 'GET':
        return render_template('index_ts.html', content = 'Hello Flask')

if __name__ == '__main__':
    # app.debug = True
    # app.run(host='127.0.0.1',port = 5000)
    app.run(host='0.0.0.0',port = 5000)

注意:
before_request 装饰器里不要有return ,如果有return 则会提前放回,而不执行请求的路由
after_request 装饰器则是要必须有 参数 和 return

4.1.2 文件名:index.html
<html lang="zh-cn">
    <head>
        <meta content="text/html; charset=utf-8" http-equiv="content-type" />
    </head>
    <body>
        {{ content }}
    </body>
</html>
4.2 访问连接:

http://127.0.0.1:5000

4.3 效果:

图中可以看到,index 是网页执行的路由,
在index 之前执行了 before 装饰器内容;
在 inxdex之后又执行了 after 装饰器内容

image


五、多个特殊装饰器,执行顺序

5.1.1 文件名:index.py
from flask import Flask, render_template, request

app=Flask(__name__)

@app.before_request
def bef_1():
    print('before_request_1')

@app.before_request
def bef():
    print('before_request_2')

@app.after_request
def aft_1(i):
    print('after_request_1')
    return i

@app.after_request
def aft_2(i):
    print('after_request_2')
    return i

@app.route('/')
def index():
    print('index')
    if request.method == 'GET':
        return render_template('index_ts.html', content = 'Hello Flask')

if __name__ == '__main__':
    # app.debug = True
    # app.run(host='127.0.0.1',port = 5000)
    app.run(host='0.0.0.0',port = 5000)
5.1.2 文件名:index.html
同 4.1.2 (略)
5.2 访问连接:

http://127.0.0.1:5000

5.3 效果:

注意: before 是按代码先后顺序来执行的;而 after 是倒序执行的(这是源码里设置的)

image





免责声明:本号所涉及内容仅供安全研究与教学使用,如出现其他风险,后果自负。




参考、来源:
https://www.bilibili.com/video/BV11Y411h71J?p=32