Flask 的消息提示语异常处理
Flaskapp.py:
from flask import Flask, flash, render_template,request,abort
app = Flask(__name__)
app.secret_key = ‘123’ #用flash时要时使用它进行加密
@app.route(‘/’)
def hello_world():
flash(‘hello feiniu’)
render_template(‘index.html’)
@app.route(‘/login’, method=[‘POST’])
def login():
form = request.form
username = form.get(‘username)
password = from.get(‘password’)
if not username:
flash(“please input username”)
return render_template(“index.html”)
if not password:
flash(“please input password”)
return render_template(“index.html”)
if username == ‘feiniuchongtian’ and password == ‘123456’:
flash(“login success”)
return render_template(“index.html”)
else:
flash(“username or password is wrong”)
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()
index.html:
……
<h1>Hello</h1>
<form action=’’/login” method=”post”>
<input type=”text” name=”username”>
<input type=”password” name=”password”>
<input type=”submit” value=”Submit”>
</form>
<h2>{{ get_flashed_messages()[0] }}</h2>
……
404.html:
……
<h1>您要找的页面去火星了</h1>
……
user.html:
……
<h1>User</h1>
……
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步