代码

from flask import Flask,render_template,request,abort

app=Flask(__name__)

@app.route('/index',methods=["GET","POST"])
def index():
    if request.method=="GET":
        return render_template("index.html")
    if request.method=="POST":
        if request.form.get("dxy")=="dou" and request.form.get("1234")=="1234":
            return "login in"
        else:
            abort(404)##或者abort(403)

##自定义错误就是通过app.errorhandler(错误类型)来实现的,其下紧跟自定义执行函数即可
@app.errorhandler(404)##当遇到上面的abort(404)时会自动执行如下的执行函数
def erroeee(error):
    return render_template("e404.html")##通过在html文件中添加img选项,设定返回的图片

@app.errorhandler(403)##当遇到上面的abort(403)时会自动执行如下的执行函数
def erroeee(error):
    return render_template("e403.html")##通过在html文件中添加img选项,设定返回的图片
##注意:其中的error参数是flask框架自动传入的,就是默认返回的那一段英文(Not Found)

app.run()

html文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<img src="/static/abc.png" width="873px" height="626px"> /*注意图片的路径,放在static中,根目录就是工程文件
</body>
</html>

2文件位置

图片在static文件夹中,e404.html在模板目录templates中

3返回自定义文字

修改执行函数即可:

from flask import Flask,render_template,request,abort

app=Flask(__name__)

@app.route('/index',methods=["GET","POST"])
def index():
    if request.method=="GET":
        return render_template("index.html")
    if request.method=="POST":
        if request.form.get("dxy")=="dou" and request.form.get("1234")=="1234":
            return "login in"
        else:
            abort(404)

@app.errorhandler(404)
def erroeee(error):
    return "自定义文字"

app.run()

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐