我正在尝试构建MNIST分类器并使用flask进行部署。我在javascript向'/'路由发出发布请求时呈现模板时遇到问题。我想将预测结果显示在同一页面上。请帮帮我。
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'GET':
return render_template("index.html", value = "Output")
if request.method == 'POST':
print("Image recieved")
data_url = request.values
x = [i for i in data_url.items()]
url = x[0][1]
newimg = Image.open(urllib.request.urlopen(url))
transform = transforms.Compose([transforms.Resize((32, 32)),
transforms.Grayscale(1),
transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,))
])
newimg = transform(newimg).unsqueeze(0)
model = get_model()
model.eval()
output = model(newimg)
pred = output.argmax(dim=1)
print("Predicted value : ", pred.item())
return render_template("index.html", value = pred)
if __name__ == "__main__":
app.run(debug = True)
这是javascript请求:
$.ajax({
type: "POST",
url: "http://localhost:5000/",
data: { 'data' : d},
}).done(function() {
console.log("Sent");
});