flask消息提示之flash

在登录界面时候出现提示性做用

Flask request render_template,flash,abort

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from flask import Flask,request,render_template,flash,abort
from flask import url_for
app=Flask(__name__)
app.secret_key='123sdfasdff'
#secret_key是进行消息加密
@app.route('/login',methods=['POST'])
def login_url():
form=request.form
username=form.get('username')
password=form.get('password')
if not username:
flash('请输入用户名')
return render_template('index.html')
if not password:
flash('请输入用户密码')
return render_template('index.html')
if username=='nuocheng' and password='123456'
flash('登陆成功')
return render_template('index.html')
else:
flash('用户名或者密码错误')
return render_template('index.html')

其中index.html里的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{content}}
<form action="/login" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="Submit">
</form>
{{get_flashed_messages()[0]}}
</body>
</html>

当url出现错误的时候,进行消息提示404异常

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from flask import Flask,request,render_template,flash,abort
from flask import url_for
app=Flask(__name__)
app.secret_key='123'
#secret_key是进行消息加密
@app.route('/users/<id>')
def users(id):
if int(id)==1:
return render_template('user.html')
else:
abort(404)
@app.errorhandler(404)
def not_fount():
return render_template('404.html')
if __name__=='__main__':
app.run()
Fork me on GitHub