Flask创建404页面

最近没事,用flask写了一个web网站,想添加一个404页面。

看了网上的一堆教程,没一个能用。

但是在404时,flask会抛出一个异常,这时候只需要异常处理就行了。

from audioop import error
import os
from flask import Flask, render_template, send_from_directory
import string

app = Flask(__name__)


@app.route('/favicon.ico')
def favicon():
    return send_from_directory(os.path.join(app.root_path, 'static'),
                               'xxx.ico',
                               mimetype='image/vnd.microsoft.icon')


@app.route('/')
def index():
    return render_template("index.html")


@app.route('/<string:postID>')
def docs(postID: string):
    try:
        return render_template(postID)
    except Exception:
        return render_template("404.html")


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug='True')

随后在templates文件夹中创建404.html,出现404时就会被导入到404.html。

其实我在这里是偷了懒的,我直接把所有错误接到了404......(本来应该用jinja2.exceptions.TemplateNotFound)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值