flask中的钩子函数hook

#_*_ encoding: utf-8 _*_   @author: ty  hery   2019/12/20

from  flask import  Flask, session, current_app, g
# g 是临时的本App里面的变量对象,通过对象的方法保存数据 如 g.username='张三',常用与一个请求之内的多个函数之间传递变量参数
# from werkzeug.routing import BaseConverter
import json
app = Flask(__name__)
app.config['SECRET_KEY'] = 'asdfsdafsdaf134561sdaf'
#  flask的session必须设置秘钥字符串:SECRET_KEY,否则报错RuntimeError: The session is unavailable because no secret key
# was set.  Set the secret_key on the application to something unique and secret.


# flask 默认把session保存到了cookie中
@app.route('/login',methods=['GET','POST'])
def login():
    # 设置session数据
    session['name'] = 'python'
    session['mobile'] = '18611111111'
    g.username = 'zhangsan'
    say_hello()
    return 'login success'

# @app.route('')
def say_hello():
    username = g.username
    print(g.username,'撒大防守打法')
    pass


@app.route('/index')
def index():
    a= 1/0
    print('index 被执行')
    return 'index page'

@app.route('/hello')
def hello():
    print('hello 被执行')
    return 'hello page'

@app.before_first_request   # 在整个视图函数第一次被访问时才执行
def handle_before_first_request():
    '''在第一次请求处理之前被执行'''
    print('handle_before_first_request被执行')

@app.before_request
def handle_before_request():
    '''在每一次请求之前被执行'''
    print('handle_before_request被执行')

@app.after_request
def handle_after_request(response):
    '''在每一次请求(视图函数处理)之后被执行,前提是视图函数没有出现异常'''
    print('handle_after_request被执行')
    return response

@app.teardown_request
def handle_teardown_request(response):
    '''在每一次请求(视图函数处理)之后被执行,无论视图函数是否出现异常,都会被执行,工作在非调试模式时,debug=False'''
    print('handle_teardown_request被执行')
    return response

if __name__ == '__main__':
    print('--哈哈01--',app.url_map,'--哈哈01--')
    # app.run(debug=True)
    app.run(debug=False)
posted @   ty1539  阅读(73)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示