钩子函数
- before_request
- before_request:在请求之前执行的
- before_request是在视图函数执行之前执行的
- before_request这个函数只是一个装饰器,它可以把需要设置为钩子函数的代码放到视图函数执行之前来执行
例子代码:
# hook.py
from flask import Flask, render_template,request,session,redirect,url_for
import os
app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(24)
@app.route('/')
def hello_world():
print('Index!')
return 'Index!'
@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():
if session.get('username'):
return '修改成功'
else:
return redirect(url_for('login'))
# before_request:在请求之前执行的
# before_request是在视图函数执行之前执行的
# before_request这个函数只是一个装饰器,它可以把需要设置为钩子函数的代码放到视图函数执行之前来执行
@app.before_request
def my_before_request():
print('hello world!')
if __name__ == '__main__':
app.run(debug = True)
# templates/login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="POST">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name = "username"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name = "password"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value = "登录"></td>
</tr>
</table>
</form>
</body>
</html>
使用钩子函数后:
# 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 'Index!'
@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():
if hasattr(g,'username'):
return '修改成功'
else:
return redirect(url_for('login'))
# before_request:在请求之前执行的
# before_request是在视图函数执行之前执行的
# before_request这个函数只是一个装饰器,它可以把需要设置为钩子函数的代码放到视图函数执行之前来执行
@app.before_request
def my_before_request():
if session.get('username'):
g.username = session.get('username')
if __name__ == '__main__':
app.run(debug = True)
<!--templates/login.html-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="POST">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name = "username"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name = "password"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value = "登录"></td>
</tr>
</table>
</form>
</body>
</html>
网页开发应该尽量避免查询数据库,这了的钩子函数可以避免过多的查询数据库
网友评论