flask 应用程序:Flask 应用程序显示 HTML 文件,而不是将其呈现为网页

flask app: Flask application is displaying the HTML file, not rendering it as a web page

提问人:Lilly 提问时间:9/13/2023 更新时间:9/14/2023 访问量:34

问:

我有一个经过训练的机器学习模型,我想在 Flask Web 应用程序中使用它。当我运行 Python 代码 (app.py) 时,Flask 应用程序将 HTML 文件显示为纯文本,而不是将其呈现为网页。下面是我的 Python 代码 (app.py) 和我的 HTML 代码 (index.html)。我是 Web 开发的新手,我正在寻求有关如何解决此问题的指导。任何协助将不胜感激。谢谢你的帮助。

from flask import Flask, request, render_template,url_for
import numpy as np
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image
import os
app = Flask(__name__)

#Load your trained CNN model
model = load_model(os.path.join('models', 'BreastCancerDetection.h5'))

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/predict', methods=['POST'])
def predict():
    # Get the uploaded image from the request
    uploaded_file = request.files['BreastUltrasoundImage']

    # Process the uploaded image
    img = image.load_img(uploaded_file, target_size=(256, 256))
    img_array = image.img_to_array(img)
    img_array = np.expand_dims(img_array / 255, axis=0)

    # Make predictions
    predictions = model.predict(img_array)



    class_labels = np.argmax(predictions, axis=1)

    return render_template('index.html', predictions=class_labels[0])


if __name__ == '__main__':
    app.run(debug=True)

我的索引.html是:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Breast Cancer Detector</title>
</head>
<body>
    <h1>Breast Cancer Prediction</h1>
    <div>
        <form action="{{ url_for('predict') }}" method="post" enctype="multipart/form-data">
            <input type="file" name="BreastUltrasoundImage" accept="image/png, image/jpeg" required>
            <button type="submit">Predict</button>
        </form>
        <h4 style="color: violet;">{{ predictions }}</h4>
    </div>
</body>
</html>

我检查了我的目录,如下所示。

project_folder/
├── app.py
├── templates/
│    └── index.html
└── models/
    └── BreastCancerDetection.h5

莉莉

HTML Flask WebDeploy

评论

0赞 pjcunningham 9/13/2023
这回答了你的问题吗?使用 Flask/Jinja2 将 HTML 传递到模板
0赞 Lilly 9/14/2023
感谢您的帮助,不幸的是,它不起作用,我的网站看起来像html文件本身<!DOCTYPE html> <html lang=“en”> <head> <title>乳腺癌检测仪</title> </head> <body> <h1>乳腺癌预测</h1> <div> <form action=“/predict” method=“post” enctype=“multipart/form-data”> <input type=“file” name=“BreastUltrasoundImage” accept=“image/png, image/jpeg“ required> <button type=”submit“>Predict</button> </form> <h4 style=”颜色:紫罗兰色;”></h4> </div> </body> </html>'

答:

0赞 Lilly 9/14/2023 #1

此问题已解决。我从 TextEdit 切换到 Atom 来编写我的 html 代码,第二个变化是用于上传图像的 python 代码:

@app.route('/upload', methods=['POST'])
def upload_file():
    uploaded_file = request.files['BreastUltrasoundImage']
    if uploaded_file:
        file_contents = uploaded_file.read()
        return file_contents

谢谢