python - 请求的 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但仍然无法使其工作。
任何帮助、提示或好的教程将不胜感激!非常感谢您,并对这篇长篇文章感到抱歉。
我的项目文件夹有以下内容:
- 应用程序.py
- model.pkl(这是我使用 Pickle 保存在磁盘上的模型)
- Powerproduction dataset.csv(原始数据集)
- 请求.py
- model.py(这是模型)
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>
解决方案
您的操作引用了您的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():
..
推荐阅读
- wordpress - Google Analytics 4 - 报告中显示的价格错误
- apache-spark - 在 dataproc 上以客户端模式运行 spark 驱动程序的位置?
- python - Python过滤JSON数组数据
- python - 多个维度的numpy数组索引
- python - 列表列表 - 比较相邻值和如果第二个元素相同 - 取旧的
- http - html中的代理url来渲染图像
- python - 已安装 numpy 但无法在 VSC 上导入
- android - 组件返回 RefreshControl 时的意外行为
- css - primeng primeflex 添加一个重置 css
- node.js - 使用 pdfmake 将多个页面添加到 pdf