日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python?flask自定義404錯誤頁面方式_python

作者:香蕉麻花皮 ? 更新時間: 2023-01-21 編程語言

python flask自定義404錯誤頁面

在用瀏覽器訪問url的時候,如果url不正確會報404錯誤,默認的404錯誤太枯燥了,這里我講述一下如何將404錯誤頁面修改為好看的404頁面

1,首先,創建一個我們希望當出現404錯誤時展示的html頁面,這里我隨便寫一個頁面內容不多定義了,意思在這就行

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>404找不到文件資源</title>
</head>
<body>
<h1><font color="red">這是一個404的錯誤頁面,出現這個頁面時說明404錯誤了</font></h1>
</body>
</html>

2,保存好我們創建的404頁面后,把這個html文件保存文件列表里,然后我們在flask添加404錯誤返回我們創建的html文件

from flask import Flask, render_template_string, abort, render_template
 
app = Flask(__name__)
 
 
@app.route('/abcd')
def abce():
    return "1234"
 
 
@app.errorhandler(404)  # 傳入錯誤碼作為參數狀態
def error_date(error):  # 接受錯誤作為參數
    return render_template("404.html"), 404  # 返回對應的http狀態碼,和返回404錯誤的html文件
 
 
if __name__ == '__main__':
    app.run(port=5000, debug=True)

3,當我們用瀏覽器請求這個實例里面的接口的時候出現了404錯誤的時候,瀏覽器上面就會顯示我們自己定義的html頁面啦

這里有些地方需要注意下?

1,我們創建的html文件要放在templates的文件目錄下面,是要完全名稱相同的目錄。

2,這個templates的文件目錄要和我們運行flask的.py文件層級相同,比如 我運行這個flask程序的文件夾名字叫app,那我們裝html的templates的文件夾要放在app的文件夾里面,并且與程序的.py文件同級

Python Flask捕獲異常,捕獲404錯誤,errorhandler(),自定義異常處理函數

demo.py(捕獲異常,自定義異常處理函數):

# coding:utf-8
 
from flask import Flask
 
app = Flask(__name__)
 
 
# 捕獲404異常錯誤
@app.errorhandler(404)
# 當發生404錯誤時,會被該路由匹配
def handle_404_error(err_msg):
    """自定義的異常處理函數"""
    # 這個函數的返回值就是前端用戶看到的最終結果 (404錯誤頁面)
    return u"出現了404錯誤, 錯誤信息:%s" % err_msg
 
 
if __name__ == '__main__':
    app.run(host="0.0.0.0", port=5000, debug=True)

總結

原文鏈接:https://blog.csdn.net/m0_58002043/article/details/121226540

欄目分類
最近更新