- 上下文处理器应该返回一个字典,字典中的
key
会被模板中当成变量来渲染
- 上下文处理器返回的字典,在所有页面中都是可以使用的
- 被这个装饰器修饰的钩子函数,必须要返回一个字典,即使为空也要返回。
# 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>
网友评论