错误处理页面未显示在烧瓶中

时间:2021-07-09 12:44:56

标签: python html flask error-handling

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

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

文件夹结构图: enter image description here -

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 错误代码

1 个答案:

答案 0 :(得分:0)

尝试使用 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')