flask的消息提示flash和abort

from flask import Flask,flash,render_template,request

app = Flask(__name__)
app.secret_key ='123'  # 此处一定要有app.secret_key, 至于为什么还没搞明白


@app.route('/')
def hello_world():
    flash("hello jikexueyuan")
    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 input username00")
        flash("please input username01")
        return render_template( "index.html")
    if not password:
        flash("please input password00")
        flash("please input password01")
        return render_template("index.html")
    if username == 'jikexueyuan' 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)   # 找不到该路由时,走这个路由
@app.errorhandler(403)   # 找不到该路由时,走这个路由
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(403)
        # abort(404)
    

if __name__ == '__main__':
    app.run()

对应的index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
    <h1>hello login</h1>

    <form action="/login" method="post">
        <input type="text" name="username">
        <input type="password" name="password">
        <input type="submit" name="Submit">
    </form>

    <h2>{{ get_flashed_messages()[0] }}</h2>
    <h2>{{ get_flashed_messages()[1] }}</h2>
    <h2>{{ get_flashed_messages() }}</h2>
</body>
</html>

404.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<h1>你要找的页面去火星了</h1>
<h2>抱歉!该页面不存在</h2>

</body>
</html>

另一个abort样式

* encoding: utf-8 * @author: ty hery 2019/12/20

from flask import Flask, request, abort, Response

from werkzeug.routing import BaseConverter

app = Flask(name)

@app.route('/login',methods=['GET'])
def login():
name = ""
pwd = ""
if name != 'zhangsan' or pwd != 'admin':
# 使用abort函数可以立即终止视图函数的执行
# 并可以返回给前端特定的信息
# 1,传递状态码信息,必须是标准的http状态码
# abort(403) # 状态码403 forbiden
# abort(404) # 状态码404 Not Found
# 2,传递响应体信息
resp = Response('login failed')
# abort(resp)
abort(Response('login failed 去死吧'))
return 'login success'

定义错误处理的方法

@app.errorhandler(404)
@app.errorhandler(403)
def handler_404_error(err):
'''自定义处理404错误的方法,这个函数返回值是前端用户看到的最终结果'''
return u"出现了404错误了,错误信息:%s" %err

if name == 'main':
print('--哈哈01--',app.url_map,'--哈哈01--')
app.run(debug=True)


写入自己的博客中才能记得长久
原文地址:https://www.cnblogs.com/heris/p/14652341.html