【问题标题】:How to set variables with a inputbox in Flask如何在 Flask 中使用输入框设置变量
【发布时间】:2021-09-16 08:04:13
【问题描述】:

我想在 Flask 中使用输入框声明变量。

但是,我收到以下错误消息:

werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: 浏览器 (或代理)发送了此服务器无法理解的请求。 KeyError:'column1'

但我明确命名了我的输入框...

我的烧瓶代码app.py

@app.route('/', methods=['POST', 'GET'])
def get_columns():
    col1 = request.form["column1"]
    col2 = request.form["column2"]
    return col1, col2

def upload_file():
    file = request.files['file']
    col1,col2 =get_columns()

    print("file:",file)

    if file.filename == '':
        flash('No file selected for uploading','red')
        # return redirect(request.url)
        return render_template('index.html', disp_div = disp_div)
    if file and allowed_file(file.filename):
        df=pd.read_csv(file)
        output=col1,col2,df["Age"].mean().round(2)
        return render_template('index.html', output=output)
        # return redirect('/')
    else:
        flash('Allowed file types are txt, pdf, png, jpg, jpeg, gif', 'red')
        # return redirect(request.url)
        return render_template('index.html')

我的神社模板index.html:

...
          <tr>
              <td><form action="/" method="POST">
                      <input name="column1" id="column1" placeholder="Spaltenname der XXX">
                  </form>
              </td>

              <td><form action="/" method="POST">
                        <input name="column2" id="column2" placeholder="Spaltenname der YYY">
                  </form>
              </td>
          </tr>
....

【问题讨论】:

    标签: python html flask


    【解决方案1】:

    您的 HTML 中有 2 个表单。 他们都指向get_columns()
    但是 python 代码假设它会同时获取它们(column1 和 column2)。
    这是错误的 - python 代码将得到 column1 或 column2 - 不是两者。

    【讨论】:

    • 我应该改变什么才能得到两列?我还尝试仅使用 column1 运行此代码。但我也得到同样的错误: KeyError: 'column1'
    • 仅使用 1 个表单(带有 2 个输入字段)而不是 2 个表单。
    猜你喜欢
    • 2020-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多