python flask-错误处理

大家好,我是python网页后端flask的讲师geo

在 Flask 中,你可以很方便地处理错误页面,例如处理用户访问不存在的 URL 时返回的 404 错误。以下是如何在 Flask 中实现自定义的 404 错误处理页面的步骤。

定义 404 错误处理函数

在 Flask 中,使用 @app.errorhandler() 装饰器来捕获 HTTP 错误,并定义一个处理函数。我们将为 404 错误创建一个自定义的错误页面。

from flask import Flask, render_template

app = Flask(__name__)

# 创建404错误处理函数
@app.errorhandler(404)
def page_not_found(error):
    return render_template('404.html'), 404

@app.route('/')
def home():
    return "Welcome to the homepage!"

if __name__ == '__main__':
    app.run(debug=True)
  • @app.errorhandler(404) 装饰器捕获 404 错误。
  • page_not_found() 函数定义了处理 404 错误的方式。它返回一个自定义的 404.html 模板,并设置 HTTP 响应代码为 404

创建 404 错误页面模板

templates/ 目录下创建一个 404.html 文件,这是你的自定义 404 错误页面的内容。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Page Not Found</title>
    <link rel="stylesheet" href="/static/style.css">
</head>
<body>
    <div class="container">
        <h1>Oops! Page not found (404)</h1>
        <p>Sorry, the page you are looking for does not exist.</p>
        <p><a href="/">Return to Homepage</a></p>
    </div>
</body>
</html>
  • 这个 HTML 模板可以是你希望展示给用户的自定义错误页面。
  • 你可以设计它,使其与网站的其他部分一致。

测试 404 错误处理

当你访问一个不存在的页面,例如 http://127.0.0.1:5000/invalid-page,你的 Flask 应用将返回自定义的 404 页面。

添加其他错误处理

你也可以类似地处理其他错误,例如 500 内部服务器错误:

@app.errorhandler(500)
def internal_error(error):
    return render_template('500.html'), 500
  • 上述代码会捕获 500 错误,并显示一个自定义的 500 错误页面。

全局的错误处理

如果你想捕获所有未预期的错误,可以定义一个通用的错误处理函数:

@app.errorhandler(Exception)
def handle_exception(error):
    # 这里你可以区分错误类型并显示不同的模板
    return render_template('error.html', error=error), 500