flask钩子函数

 

@app.context_processor
def context_processor():
    return {"current_user":"zhiliao"}#这里必须有返回值,而且返回值必须是字典


#下面错误的写法
@app.context_processor
def context_processor_error():
    if hasattr(g,'user'):
        return {"current_user":g.user}#不能这样写,函数没有返回值,默认返回None
    return {}#这样写是正确的

@app.route('/')
def hello_world():
    #就是显示当前app的名字
    # print(current_app.name)
    # print(url_for('my_list'))
    # username = request.args.get('username')
    # g.username = username #把username绑定到全局变量上,任何地方都可以用
    # log_a()
    # log_b()
    # log_c()
    if hasattr(g,'user'):
        print(g.user)
    abort(404)#如果使用abort这个函数,手动报一个404的错误
    #然后执行@app.errorhandler(404)这个装饰下面的代码
    return render_template('index.html')
@app.errorhandler(500)#用来设置500,404错误
def server_error(error):
    return render_template('500.html')


@app.errorhandler(404)
def page_no_find(error):
    return render_template('404.html')
原文地址:https://www.cnblogs.com/wuheng-123/p/9749584.html