【问题标题】:Post output from user input on same web page using HTML and Flask (python)使用 HTML 和 Flask (python) 在同一网页上发布用户输入的输出
【发布时间】:2021-09-01 14:44:17
【问题描述】:

我正在尝试根据使用 HTML 和 Flask 的用户输入在网页上发布输出。以下是代码。

app.py:

import pandas as pd
from flask import Flask, render_template, request

app = Flask(__name__)



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

        if request.method == 'POST':
                x_in = request.form.get('x_in')
        elif request.method == 'GET':
                data = pd.DataFrame({'data':[int(x_in)*10]})
                return render_template('index.html', data=data.to_html())


if __name__ == '__main__':

        app.run(host='0.0.0.0', port=80, debug=False)

我使用了以下 2 个 html 文件进行渲染。

模板.html:

html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Flask Parent Template</title>
  </head>
  <body>
    <header>
      <div class="container">
        <h1 class="logo">Trial</h1>
        <strong><nav>
            <ul class="menu">
              <li><a href="{{ url_for('predict') }}">Home</a></li>
            </ul>
          </nav></strong>
        </div>
      </header>

      {% block content %}
      {% endblock %}

    </body>
  </html>

index.html:

html>
  <title>About the App</title>
  <head>
  <body>
    {% extends "template.html" %}
    {% block content %}

    <form action = / method="POST">
      <label for="x_in">INPUT:</label>
      <input type="text" name="x_in" id="x_in" size="15">
      <input type="submit" value="Generate Result" />
    </form>
        {{data|safe}}
    {% endblock %}
  </body>
</html>

但是,我收到如下错误: UnboundLocalError:赋值前引用了局部变量“x_in”

这是一个非常简单的代码,我不确定为什么“POST”方法没有接收到用户的输入。我的猜测是这是一个微不足道的错误,但我们将不胜感激。

【问题讨论】:

  • action /周围没有引号
  • 我认为这不是问题所在。添加了引号,错误仍然存​​在
  • 有get请求时使用x_in,但通过post请求发送x_in
  • 那么代码应该是什么?

标签: python html flask web-applications


【解决方案1】:

据我说,您想显示一个输入表单,用户输入 imput 并获得结果

@app.route('/', methods=['GET', 'POST'])
def predict():
      if request.method == 'POST':
           x_in = request.form.get('x_in')
           data = pd.DataFrame({'data':[int(x_in)*10]})
           return render_template('index.html', data=data.to_html())
      return render_template("index.html")

在神社中这样做

{% if data %}
{{data|safe}}
{% endif %}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-02
    • 2020-09-26
    • 2019-09-10
    • 2021-12-06
    • 1970-01-01
    • 2011-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多