【问题标题】:How do I print a user's input in a form onto the website screen如何将表单中的用户输入打印到网站屏幕上
【发布时间】:2021-12-23 05:00:05
【问题描述】:

我正在用flask和python构建一个网站,我想将用户的输入存储在一个变量中,然后将其输出到网站屏幕上。

这是我的 HTML 代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home</title>
</head>
<body>
    <div><h1>Home Page</h1>
    <p>Hello, {{ name }}</p>
    </div>

    <form>
        <label for="fname">Enter Sq. ft.</label><br>
        <input type="text" id="estimate" name="estimate" value="Ex. 1000"><br>
        <input type="submit" value="Calculate Estimate">
    </form>

    <a href="/my-link/">Click me</a>
</body>
</html>

这是我的 python/flask 代码:

from flask import Flask, render_template

app = Flask(__name__)

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

@app.route('/my-link/')
def my_link():
    temp = 0
    for i in range(10):
        temp = i

    return str(temp)

if __name__ == '__main__':
    app.run(debug=True, port=8000)

当我运行它时,我看到的是:

当我输入 54 并点击“计算估计”时,我不明白为什么我的搜索栏中会出现 http://127.0.0.1:8000/?estimate=54,我不明白它为什么会出现在那里。我怎样才能获得 54 并将其打印在网站屏幕上?

【问题讨论】:

  • 表单元素通过查询参数将其值提交给域(如您的案例所示)。默认情况下form 使用GET 提交它的请求。如果要禁用提交,请添加 onSubmit 处理程序并阻止事件传播。您还可以通过这种方式访问​​您的数据。
  • @Urmzd 默认好像是request.args吧?
  • @collinsmarra 查询参数编码为request.args。更多信息可以找到here

标签: python html forms flask


【解决方案1】:

如果您要提交敏感数据,我建议您使用POST,但GET 就足够了。

为了解决您的问题,我们必须首先指定一个操作端点(默认情况下,它是/,它将过多的责任加载到一个端点上)。

  <form action="/calculate-estimate">
      <label for="fname">Enter Sq. ft.</label><br>
      <input type="text" id="estimate" name="estimate" value="Ex. 1000"><br>
      <input type="submit" value="Calculate Estimate">
  </form>

其次,我们需要创建一个FLASK端点来处理表单数据。

@app.route("/calculate-estimate", methods=["GET"])
def calculate_estimate():
    estimate = request.args.get("estimate")
    ## Use your data however you desire.

这应该足以解决您的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-09
    • 1970-01-01
    • 2016-06-15
    • 2011-03-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    相关资源
    最近更新 更多