【问题标题】:I get 404 error on the background image when I run my website当我运行我的网站时,背景图像上出现 404 错误
【发布时间】:2021-08-09 03:36:27
【问题描述】:

我创建了一个烧瓶服务器实例并上传了一个机器学习模型,因此我可以发送一个包含图片的发布请求并将结果返回到 JSON 文件中,我在一个包含两条路由的网站上对其进行了测试(我构建了使用 HTML 的页面)并且它工作正常,我想向网站添加背景图像,但是当我在 CMD 中运行 python 文件时,我在该图像上收到 404 错误。任何帮助将不胜感激。

这是其中一个网页的 HTML 代码

<!DOCTYPE html>
<html>
<head>
    <title>prediction</title>
</head>
<style>
    h3 {color:rgb(138, 34, 34); font-size: 25px;}
  </style>
<body style="background-image:url(a.jpg);background-size: 100%; color: white; position: absolute; top: 15%; left: 45%; font-size: 16px; line-height: 1.4;">

    <center>
        <h1>Your prediction is:</h1>

        

        <h3>{{data}}</h3>

    </center>

</body>
</html>

这是烧瓶服务器的代码

from flask import Flask, render_template, request, jsonify
import cv2
import numpy as np
import pandas as pd
import tensorflow
from tensorflow import keras
from tensorflow.python.keras import backend as k

app = Flask(__name__)

model = tensorflow.keras.models.load_model('model.h5')


@app.route('/')
def index():
    return render_template("index.html", data="hey")


@app.route("/prediction", methods=["POST"])
def prediction():

    predd="Benign"
    
    img = request.files['img']
    
    img.save("img.jpg")

    image = cv2.imread("img.jpg")

    image = cv2.resize(image, (224,224))

    image = np.reshape(image, (1,224,224,3))

    pred = model.predict(image)

    preddd = pred > 0.5
    pre= pred*100
    s= "%"
    if(preddd):
        predd="Malignant"

    print("prediction is:")
    print(predd)
    print("percentage is:")
    print(str(pre) +s)
    print(" ")

    #return jsonify({"prediction is": predd,})
    return render_template("prediction.html", data=predd)
    


if __name__ == "__main__":
    app.run(debug=False,host='192.168.1.111',port=5000)

这是我的 CMD 截图

【问题讨论】:

    标签: python html css flask http-status-code-404


    【解决方案1】:

    确保图片存在于static子目录中,所以路径为:

    static/a.jpg

    验证这个可以直接在http://192.168.1.111/static/a.jpg加载

    然后更改 CSS 以支持此功能:

    background-image:url("/static/a.jpg")
    

    【讨论】:

    • 并将app = Flask(__name__)更改为app = Flask(__name__, static_folder='./static')
    • @JoshLiu static_folder 默认为 'static',因此除非您希望在磁盘上调用该目录有所不同,否则更改此设置没有意义。
    【解决方案2】:

    另一种选择:添加以下路线,您就可以开始了。

    @app.route("/a.jpg", methods=["GET"])
    def image():          
        return send_from_directory('path/to/image', 'a.jpg')
    

    或者如果名称 a.jpg 不固定,请执行以下操作:

    @app.route("/<name>", methods=["GET"])
    def image(name):          
        return send_from_directory('path/to/image', name)
    

    【讨论】:

      猜你喜欢
      • 2018-06-07
      • 2022-07-21
      • 1970-01-01
      • 2022-01-02
      • 2021-12-19
      • 2017-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多