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