一、消息提示
Flask提供消息闪现机制,方便在应用中消息提示;
首先导入flash方法,再对secret_key进行赋值,以对消息加密;
然后定义一个路由,使用flash方法,并返回模板;
flaskApp.py代码如下,功能是对输入的用户名和密码进行相应提示;
#-*-coding:utf8-*-
from flask import Flask, flash, render_template,request
app = Flask(__name__)
app.secret_key = '123'
@app.route('/')
def hello_user():
flash("Welcomt to China")
return render_template("index.html")
@app.route('/login', methods=['POST'])
def login():
form=request.form
username=form.get('username')
password=form.get('password')
if not username:
flash("Please enter username")
return render_template("index.html")
if not password:
flash("Please enter password")
return render_template("index.html")
if username=="wencheng" and password=="123":
flash("Login succeed")
return render_template("index.html")
else:
flash("Username or password is not correcct")
return render_template("index.html")
if __name__ == '__main__':
app.run()
indexhtml文件代码如下,呈现给用户的样式在这里指定;
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>Hello Login</h1>
<!--
form标签的action属性是指提交表单时将数据提交到指定页面,这里是/login页面
form标签的method属性是规定如何发送表单数据,有post/get
-->
<form action="/login" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" name="submit">
</form>
<h3>{{get_flashed_messages()[0]}}</h3>
</body>
</html>
例举几个样式:
二、异常处理
对于不存在的文件名部分,默认处理机制显示如下;
对于用户来说,是页面不友好的;
使用装置器errorhandler捕获错误,然后对指定错误进行处理;
flaskApp.py代码如下;
#-*-coding:utf8-*-
from flask import Flask, flash, render_template,request
app = Flask(__name__)
app.secret_key = '123'
@app.route('/')
def hello_user():
flash("Welcomt to China")
return render_template("index.html")
@app.errorhandler(404)
def not_found(e):
return render_template("404.html")
if __name__ == '__main__':
app.run()
捕获的404显示页面代码如下;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>你要找的页面去火星了</h1>
<h2>抱歉,该页面不存在</h2>
</body>
</html>
显示效果如下:
三、抛出异常
有时根据需求,需要主动抛出异常,则首先导入abort方法,再使用abort方法抛出指定异常;
flaskApp.py代码如下:
#-*-coding:utf8-*-
from flask import Flask, flash, render_template,request, abort
app = Flask(__name__)
app.secret_key = '123'
@app.route('/')
def hello_user():
flash("Welcomt to China")
return render_template("index.html")
@app.errorhandler(404)
def not_found(e):
return render_template("404.html")
@app.route('/users/<user_id>')
def users(user_id):
if int(user_id) == 1:
return render_template("user.html")
else:
#主动抛出异常
abort(404)
if __name__ == '__main__':
app.run()