首页 > 解决方案 > 请求的 URL 不允许该方法:使用 Flask POST 方法

问题描述

首先,我对此很陌生,所以我希望我能尽我所能解释自己。我在大学有一个项目,我们正在使用 Flask 创建一个 Web 应用程序。

我们需要收集用户的输入,然后使用我创建的模型预测某些值,用 Pickle 保存并将其加载到我的应用程序中。现在当我访问我的页面时,我可以看到主页显示并且我可以输入输入但随后“预测”页面未显示并给我错误“请求的 URL 不允许该方法”。我已经咨询并遵循不同的方法来做到这一点,例如来自这篇文章:https ://www.kdnuggets.com/2019/10/easily-deploy-machine-learning-models-using-flask.html和这个https: //towardsdatascience.com/deploy-a-machine-learning-model-using-flask-da580f84e60c但仍然无法使其工作。

任何帮助、提示或好的教程将不胜感激!非常感谢您,并对这篇长篇文章感到抱歉。

我的项目文件夹有以下内容:

import numpy as np
from flask import Flask, request, jsonify, render_template
import pickle

app = Flask(__name__)
model = pickle.load(open('model.pkl', 'rb'))

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

@app.route('/predict',methods=['POST'])
   def predict():
       int_features = [float(x) for x in request.form.values()]
       final_features = [np.array(int_features)]
       prediction = model.predict(final_features)
       output = round(prediction[0], 2)
       return render_template('index.html', prediction_text='Power output should be $ {}'.format(output))
@app.route('/results',methods=['POST'])
    def results():
        data = request.get_json(force=True)
        prediction = model.predict(final_features)

        output = prediction[0]
        return jsonify(output)


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

    import requests

    url = 'http://127.0.0.1:5000/'
    r = requests.post(url,json={'wind speed':})

    print(r.json())

    import numpy as np
    import matplotlib.pyplot as plt
    import pandas as pd
    import pickle

    dataset = pd.read_csv('Powerproduction dataset.csv')

    X = dataset.loc['speed']

    y = dataset.loc['power']

    from sklearn.linear_model import LinearRegression
    regressor = LinearRegression()

    regressor.fit(X.values.reshape(-1,1), y)

    pickle.dump(regressor, open('model.pkl','wb'))

    model = pickle.load(open('model.pkl','rb'))
    print(model.predict(np.array([[34.00]]))[0])
<head>
  <meta charset="UTF-8">
  <title>Wind speed and power output prediction</title> 
</head>

<body style="background: #000;">
    <h1>Power output predictions</h1>

     <!-- Main Input For Receiving Query to our ML -->
    <form action="{{ url_for('home')}}"method="post">
        < />
        <input type="text" name="wind speed" placeholder="wind speed" required="required" />
        <button type="submit" class="btn btn-primary btn-block btn-large">Predict power output</button>
    </form>

   <br>
   <br>
   {{ prediction_text }}

 </div>
</body>
</html>

标签: pythonnumpyflask

解决方案


您的操作引用了您的home路线:

action="{{ url_for('home')}}

您希望它指向您的predict路线:

action="{{ url_for('predict') }}"

您还应该有一个空格"(但大多数浏览器都会正确解析):

action="{{ url_for('predict') }}" method="post">

< />你的空index.html也应该被删除。

我也会修复缩进,通常你不会缩进,@app.route(..)并确保在函数结束和下一条路径之间有一个空行以使其更具可读性(有一个名为 PEP-8 的标准定义了 Python 代码应该如何看 - 如果您不符合要求,Pycharm 和其他编辑器通常会给您提示):

@app.route('/predict',methods=['POST'])
def predict():
    ..

@app.route(...)
def foo():
    ..

推荐阅读