Python武器库开发-flask篇之error404(二十七)

flask篇之error404(二十七)

首先,我们先进入模板的界面创建一个404的html页面

python 复制代码
cd templates 
vim 404.html

404.html的内容如下:

html 复制代码
<h1>error!!!</h1>

在 Flask 应用程序中,当用户访问一个不存在的页面的时候,会出现 404 错误。为了更好地处理这些错误,Flask 提供了以下两种方式:

  1. 使用 Flask 提供的错误处理机制

Flask 提供了一个 @app.errorhandler 装饰器,可以用于处理应用程序的错误。当应用程序出现错误时,可以使用该装饰器来显示一个自定义的错误页面。

以下是一个处理 404 错误的示例代码:

python 复制代码
#!/usr/bin/env python3
from flask import Flask, render_template

app = Flask(__name__)

@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404
    
if __name__ == '__main__':
    app.run(debug=True)

在上面的代码中,@app.errorhandler(404) 装饰器用于处理 404 错误,render_template() 函数用于渲染一个自定义的模板页面并返回给用户。

我们保存代码,运行该脚本:

python 复制代码
python3 app.py

任意浏览器输入URL http://127.0.0.1:5000/(任意错误的参数),则浏览器返回给我们一个error!!!的自定义的响应界面

  1. 使用 Flask-Bootstrap 扩展

Flask-Bootstrap 是一个为 Flask 提供前端框架 Bootstrap 支持的扩展。它提供了一个 bootstrap/base.html 模板文件,该文件用于渲染网页的基本结构,并包含了一些常用的 Bootstrap 样式和 JavaScript 库。

可以通过直接继承 bootstrap/base.html 模板文件来创建自定义的错误页面,如下所示:

python 复制代码
{% extends 'bootstrap/base.html' %}

{% block title %}Page Not Found{% endblock %}

{% block content %}
<div class="container">
    <div class="jumbotron text-center">
        <h1>404</h1>
        <p>Page Not Found</p>
    </div>
</div>
{% endblock %}

在上面的代码中,extends 关键字用于继承 bootstrap/base.html 模板文件,title 块用于设置网页的标题,content 块用于设置网页的内容。

然后,在应用程序中,可以使用以下代码来注册处理 404 错误的页面:

python 复制代码
#!/usr/bin/env python3
from flask import Flask, render_template
from flask_bootstrap import Bootstrap

app = Flask(__name__)
bootstrap = Bootstrap(app)

@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404
    
if __name__ == '__main__':
    app.run(debug=True)

以上就是处理 Flask 中 404 错误的两种方式。用户可以根据自己的需求选择一种或多种方式来处理错误。

相关推荐
金銀銅鐵6 小时前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup1111 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi0013 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵14 小时前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf15 小时前
Agent 流程编排
后端·python·agent
copyer_xyf16 小时前
Agent RAG
后端·python·agent
copyer_xyf16 小时前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf16 小时前
Agent 记忆管理
后端·python·agent
星云穿梭1 天前
用Python写一个带图形界面的学生管理系统——完整教程
python