常用重点:
1.上下文处理器应该返回一个字典,字典中的key
会被模板中当成变量来渲染
2.上下文处理器返回的字典,在所有页面中都是可以使用的
3.被这个装饰器修饰的钩子函数,必须要返回一个字典,即使为空也要返回。
简介:
app_context_processor在flask中被称作上下文处理器,借助app_context_processor我们可以让所有自定义变量在模板中可见,如下面的代码,我们将email作为一个变量在所有模板中可见:
@main.app_context_processor def admin_email(): email='879651072@qq.com' return dict(email='879651072@qq.com')
注意点:
1.app_context_processor作为一个装饰器修饰一个函数
2.函数的返回结果必须是dict,届时dict中的key将作为变量在所有模板中可见。
定义了上述变量email中之后,我们直接在html模板中进行使用:
管理员邮箱:<a href="mailto:{{email}}">{{email}}</a>
例子:
# hook.py from flask import Flask, render_template,request,session,redirect,url_for,g import os app = Flask(__name__) app.config['SECRET_KEY'] = os.urandom(24) @app.route('/') def hello_world(): print('Index!') return render_template('index.html') @app.route('/login/',methods = ['GET','POST']) def login(): print('login') if request.method == 'GET': return render_template('login.html') else: username = request.form.get('username') password = request.form.get('password') if username == 'zhiliao' and password == '111111': session['username'] = 'zhiliao' return '登录成功' else: return '用户名或者密码错误!' @app.route('/edit/') def edit(): return render_template('edit.html') # before_request:在请求之前执行的 # before_request是在视图函数执行之前执行的 # before_request这个函数只是一个装饰器,它可以把需要设置为钩子函数的代码放到视图函数执行之前来执行 @app.before_request def my_before_request(): if session.get('username'): g.username = session.get('username') @app.context_processor def my_context_processor(): return {'username':'test'} if __name__ == '__main__': app.run(debug = True)
<!--templates/index.html--> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {{ username }} </body> </html>
<!--templates/edit.html--> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {{ username }} </body> </html>