建站服务网络公司,天元建设集团有限公司六公司,php购物网站设计代码,h5网页制作视频教程flask篇之error404(二十七)
首先#xff0c;我们先进入模板的界面创建一个404的html页面
cd templates
vim 404.html404.html的内容如下#xff1a;
h1error!!!/h1在 Flask 应用程序中#xff0c;当用户访问一个不存在的页面的时候#xff0c;会出现 4…flask篇之error404(二十七)
首先我们先进入模板的界面创建一个404的html页面
cd templates
vim 404.html404.html的内容如下
h1error!!!/h1在 Flask 应用程序中当用户访问一个不存在的页面的时候会出现 404 错误。为了更好地处理这些错误Flask 提供了以下两种方式
使用 Flask 提供的错误处理机制
Flask 提供了一个 app.errorhandler 装饰器可以用于处理应用程序的错误。当应用程序出现错误时可以使用该装饰器来显示一个自定义的错误页面。
以下是一个处理 404 错误的示例代码
#!/usr/bin/env python3
from flask import Flask, render_templateapp Flask(__name__)app.errorhandler(404)
def page_not_found(e):return render_template(404.html), 404if __name__ __main__:app.run(debugTrue)在上面的代码中app.errorhandler(404) 装饰器用于处理 404 错误render_template() 函数用于渲染一个自定义的模板页面并返回给用户。
我们保存代码运行该脚本
python3 app.py任意浏览器输入URL http://127.0.0.1:5000/(任意错误的参数)则浏览器返回给我们一个error的自定义的响应界面 使用 Flask-Bootstrap 扩展
Flask-Bootstrap 是一个为 Flask 提供前端框架 Bootstrap 支持的扩展。它提供了一个 bootstrap/base.html 模板文件该文件用于渲染网页的基本结构并包含了一些常用的 Bootstrap 样式和 JavaScript 库。
可以通过直接继承 bootstrap/base.html 模板文件来创建自定义的错误页面如下所示
{% extends bootstrap/base.html %}{% block title %}Page Not Found{% endblock %}{% block content %}
div classcontainerdiv classjumbotron text-centerh1404/h1pPage Not Found/p/div
/div
{% endblock %}在上面的代码中extends 关键字用于继承 bootstrap/base.html 模板文件title 块用于设置网页的标题content 块用于设置网页的内容。
然后在应用程序中可以使用以下代码来注册处理 404 错误的页面
#!/usr/bin/env python3
from flask import Flask, render_template
from flask_bootstrap import Bootstrapapp Flask(__name__)
bootstrap Bootstrap(app)app.errorhandler(404)
def page_not_found(e):return render_template(404.html), 404if __name__ __main__:app.run(debugTrue)以上就是处理 Flask 中 404 错误的两种方式。用户可以根据自己的需求选择一种或多种方式来处理错误。