【问题标题】:trying to pass value from a textbox into a variable in python with flask尝试使用烧瓶将文本框中的值传递给python中的变量
【发布时间】:2020-04-17 00:02:06
【问题描述】:

我有一个带有文本框的简单前端,单击后,我希望将该文本框中的任何内容传递到变量中。我将如何去做这件事。

这是我的 app.py 文件的一点点:

input = input('Type headline here')
#MAKING PREDICTIONS BASED ON NEW DATA
predict = model2.predict(input)
print(predict)

#MAKING THE FRONTEND

app = Flask(__name__)
Bootstrap(app)


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

@app.route('/', methods = ["POST"])
def predict2():
    text = request.form["input"]
    #return render_template('index.html', prediction = predict)
    return text


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

这是我的 html 文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>FAKE NEWS DETECTOR</title>
</head>
<body>
<h1> Enter the news headline to see if its fake or real</h1>

<form method="POST">
        <input name = 'input'>
        <input type = "submit">


</form>
</body>
</html>

我希望将用户输入存储到输入变量中,并返回另一个输出。通过我现在的设置,我只收到“不允许的方法,请求的 url 不允许方法”消息。我将如何解决这个问题?

【问题讨论】:

  • 同一个 URL 有两条路由。那是行不通的。此外,您允许 "POST " 方法而不是 "POST";两者是一回事。

标签: python html flask input backend


【解决方案1】:

每个 URL 应该只有一个路由,并检查 request 对象以确定如何继续

@app.route('/', methods=['GET', 'POST'])
def predict():
    if request.method == 'POST':
        # get the form data
        text = request.form['input']
        # do your prediction here
        render_template('index.html', text=text)
    return render_template('index.html')

【讨论】:

  • 当我使用这段代码时,我只是得到一个内部服务器错误
  • 如果您使用debug=True 运行您的代码,它应该会告诉您更多信息,它在终端输出中是否还有其他内容?应该注意,这应该是唯一的路线,并且您应该删除您在问题中发布的其他两条路线并仅替换为这条路线
猜你喜欢
  • 1970-01-01
  • 2018-04-08
  • 2017-11-19
  • 2020-12-21
  • 1970-01-01
  • 2017-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多