【问题标题】:Error handling page is not displayed in flask烧瓶中不显示错误处理页面
【发布时间】:2021-07-09 12:44:56
【问题描述】:

我遵循了 Flask 教程,我想使用错误处理 404 和 500 来显示自定义网页。我在 static/templates 文件夹中创建了 404.html 和 500.html。

当我尝试输入错误的网址时,例如“http://127.0.0.1:5000/wfefef”,我只得到一个空白页面和控制台错误:127.0.0.1 - - [09/Jul/2021 14 :35:12] “GET /wfefef HTTP/1.1” 404 而不是给我自定义 html 页面来处理此类错误。我做错了什么?

文件夹结构图: -

app.py的代码如下:

import os
import pickle
from flask import Flask, flash, request, redirect, render_template
from flask_bootstrap import Bootstrap
from sklearn.feature_extraction.text import CountVectorizer
from werkzeug.utils import secure_filename
from ocr import ocr_processing
import werkzeug


UPLOAD_INPUT_IMAGES_FOLDER = '/static/uploads/'
ALLOWED_IMAGE_EXTENSIONS = set(['png', 'jpg', 'jpeg'])

app = Flask(__name__)
bootstrap = Bootstrap(app)
app.secret_key = ''
app.config['MAX_CONTENT_LENGTH'] = 1024 * 1024
@app.errorhandler(404)
def not_found_error(error):
    return render_template('404.html'), 404


@app.errorhandler(werkzeug.exceptions.HTTPException)
def internal_error(error):
    return render_template('500.html'), 500

404.html

{% extends "base.html" %} {%block content %}
<h1>File Not Found</h1>
<p><a href="{{ url_for('upload') }}">Back</a></p>

{% endblock %}

我有一个类似的 500 错误代码

【问题讨论】:

  • 你需要把你的 404.html 和 500.html 放在 templates 文件夹而不是 static/templates 文件夹中。
  • 即使将它们放在模板文件夹中,它们似乎仍然无法工作@charchit
  • 我还上传了文件夹结构的图像。它不再在静态文件夹中。 @charchit
  • 其他页面是否在您的应用中呈现?你的 app.py 在哪里?
  • 是的,其他页面工作正常。 App.py 位于主目录本身内。 @charchit

标签: python html flask error-handling


【解决方案1】:

尝试使用MVC 模式让你的应用程序在烧瓶上。创建这样的结构

| -- app
      | -- main
           | -- __init__.py
           | -- errors.py
           | -- views.py
      | -- templates
           | -- errors
                | -- 403.html
                | -- 404.html
                | -- 500.html

__init__.py文件

#!/usr/bin/env python
# coding: utf-8
from flask import Blueprint
main = Blueprint('main', __name__)
from . import views

error.py文件

#!/usr/bin/env python
# coding: utf-8
from . import main
from flask import render_template


@main.app_errorhandler(404)
def page_404(e):
    return render_template('errors/404.html'), 404


@main.app_errorhandler(500)
def page_500(e):
    return render_template('errors/500.html'), 500


@main.app_errorhandler(403)
def page_not_found(e):
    return render_template('errors/403.html'), 403

views.py文件

#!/usr/bin/env python
# coding: utf-8
from . import errors  # it is important

@main.route("/", methods=['GET'])
def index():
    return render_template('index.html')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-31
    • 1970-01-01
    • 2015-11-09
    • 1970-01-01
    相关资源
    最近更新 更多