栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 软件开发 > 后端开发 > Python

Flask创建404页面

Python 更新时间:发布时间: 百科书网 趣学号

最近没事,用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('/')
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)

转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/1071526.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号