zoukankan      html  css  js  c++  java
  • 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)
    
    写入自己的博客中才能记得长久
  • 相关阅读:
    Problem 3
    Problem 2
    Problem 1
    Python基础 装饰器
    算法——狄克斯特拉算法
    A Knight's Journey POJ 2488
    多校10 1007 CRB and Queries
    多校9 1007 Travelling Salesman Problem
    多校8 1008 Clock
    多校7 1005 The shortest problem
  • 原文地址:https://www.cnblogs.com/heris/p/14650684.html
Copyright © 2011-2022 走看看