【问题标题】:Flask- The requested URL was not found on the serverFlask-在服务器上找不到请求的 URL
【发布时间】:2021-12-27 07:21:00
【问题描述】:

我认为这是一个简单的问题,但我有点卡在这里。

我正在尝试在 Flask 中部署 keras 模型。我的主要建议是练习api。

但每当我尝试打开给定的本地主机 ID 时,我都会不断收到此错误。

Not Found

The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.

我是否遗漏了代码中的任何内容?

我在下面提到了我的代码:

from numpy.lib.twodim_base import tri
import pandas as pd
import numpy as np
import flask
from tensorflow.keras.models import load_model
import joblib
import csv
import codecs
import warnings




def warn(*arg, **kwargs):
    pass

warnings.warn = warn

#initialize the flask application

app = flask.Flask(__name__)

#load the pre-trained model

def define_model():
    global model
    model = load_model('./model/anomaly_model.h5')
    return print("Model is loaded")


limit = 10

@app.route("/submit", methods=["POST"])

def submit():
    #initialize the data dictionary that will be returned in the response
    data_out = {}
    #load the data file from our endpoint
    if flask.request.method == "POST":
        #read the data file
        file = flask.request.files['data_file']
        if not file:
            return "No file submitted"
        data = []
        stream, = codecs.iterdecode(file.stream, 'utf-8')
        for row in csv.reader(stream, dialect=csv.excel):
            if row:
                data.append(row)
                
        #convert input data to pandas dataframe
        
        df = pd.DataFrame(data)
        df.set_index(df.iloc[:, 0], inplace=True)
        df2 = df.drop(df.columns[0], axis=1)
        df2 = df2.astype(np.float64)
        
        #normalize the data
        scaler = joblib.load('./data/combined.csv')
        X = scaler.transform(df2)
        X = X.reshape(X.shape[0], 1, X.shape[1])
    
        data_out['Analysis'] = []
        preds = model.predict(X)
        preds = preds.reshape(preds.shape[0], preds.shape[2])
        preds = pd.DataFrame(preds, columns=df2.columns)
        preds.index = df2.index
        
        scored = pd.DataFrame(index=df2.index)
        yhat = X.reshape(X.shape[0], X.reshape[2])
        scored['Loss_mae'] = np.mean(np.abs(yhat - preds), axis=1)
        scored['Threshold'] = limit
        scored['Anomaly'] = scored['Loss_mae'] > scored['threshold']
        print(scored)
    
    #determine of an anomaly was detected
    
    triggered = []
    for i in range(len(scored)):
        temp = scored.iloc[i]
        if temp.iloc[2]:
            triggered.append(temp)
    print(len(triggered))
    if len(triggered) > 0:
        for j in range(len(triggered)):
            out = triggered[j]
            result = {"Anomaly": True, "Value":out[0], "filename":out.name} 
            data_out["Analysis"].append(result)
    else:
        result = {"Anomaly":"No Anomalies Detected"}
        data_out["Analysis"].append(result)
    print(data_out)
        
    return flask.jsonify(data_out)

if __name__ == "__main__":
    print(("* Loading the Keras model and starting the server ...."
          "Please wait until the server has fully started before submitting"))
    define_model()
    app.run(debug=True)

实际上我是 Flask 的新手。 这是我的第一次尝试。我也尝试给 app.run(host='0.0.0.0') 但对我不起作用。我能得到一些帮助吗???

这是来自终端的日志:

* Loading the Keras model and starting the server ....Please wait until the server has fully started before submitting
2021-12-27 16:29:45.158086: I tensorflow/core/platform/cpu_feature_guard.cc:151] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX2 FMA
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
Model is loaded
 * Serving Flask app 'implimentation' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
* Loading the Keras model and starting the server ....Please wait until the server has fully started before submitting
2021-12-27 16:29:49.283527: I tensorflow/core/platform/cpu_feature_guard.cc:151] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX2 FMA
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
Model is loaded
Model is loaded
 * Debugger is active!
 * Debugger PIN: 114-980-010
127.0.0.1 - - [27/Dec/2021 16:05:37] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [27/Dec/2021 16:05:38] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [27/Dec/2021 16:05:53] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [27/Dec/2021 16:05:56] "GET / HTTP/1.1" 404 -

希望得到帮助

谢谢

【问题讨论】:

  • 服务器日志说什么?在你运行python app.py 之后?
  • 它是这样的:[27/Dec/2021 16:07:21] "GET / HTTP/1.1" 404 -
  • 我会添加完整的日志,请稍等。
  • 我的意思是,当您启动服务器时.. 服务器说“在 xyz 服务”对吗?
  • 我添加了日志。你能检查一下吗?

标签: python flask


【解决方案1】:

您应该尝试将@app.route("/submit", methods=["POST"]) 更改为@app.route("/", methods=["POST"])。也就是说,删除submit。当您运行程序时,默认位置是http://127.0.0.1:5000/,但您正在尝试访问http://127.0.0.1:5000/submit

要么每次访问http://127.0.0.1:5000/submit,要么将url中的submit去掉,这样更容易,每次访问默认位置。

这个answer 非常相似。

【讨论】:

  • 这个有帮助。但除了 {},我在页面中看不到任何结果。
  • 这可能是其他代码的问题。如果它返回的值不是没有找到 URL(即预期值),那么烧瓶路由正在工作。
  • 我无法在烧瓶页面中打印输出。我将上传一个新问题。非常感谢。
【解决方案2】:

这取决于你想要什么。

您拥有的唯一路由是/submit POST 路由。

您收到该错误是因为您访问的是 /(GET) 路由而不是 /submit(POST)

添加一条新路由来查看您的服务器是否正常运行

@app.route("/")
def home():
    return 'home'

或使用邮递员等工具,将/submit 路由作为 POST 请求。

还要记住端口是 5000。

【讨论】:

  • 我知道了,我试过了,但它只打印在我的网络应用程序中的 {}。我错过了什么吗?
【解决方案3】:

/submit 端点不是您可以通过键入 http://localhost:5000/submit 来访问的常规 GET 请求。

它显然期待文件上传。使用上传文件按钮制作一个虚拟前端,或者使用 Postman 创建一个带有必要标志的 Post 请求以上传文件,当然,请提供文件路径

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-09
    相关资源
    最近更新 更多