【问题标题】:BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand. KeyError: 'search'BadRequestKeyError:400 错误请求:浏览器(或代理)发送了此服务器无法理解的请求。键错误:“搜索”
【发布时间】:2020-12-16 19:09:20
【问题描述】:

App.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="." method="post">
        Search: <input type="text" name="search">
        <input type="submit" value="Show">
   </form>
</body>
</html>

main.py

from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def index():
    return render_template('index.html')

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

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

@app.route('/App', methods=['POST', 'GET'])
def App():
    search = request.form['search']
    return render_template('output.html', n=search)

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

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

我已经创建了多个 html 页面

我想打印消息,从 TextBox(上面的代码)请求并打印到另一个 html 页面

我尝试使用 request.form.get('search') 但它返回 null

如果我使用 request.form.get('search', FALSE or TRUE) 它返回 FALSE 或 TRUE

我也使用 if else 循环来指定 GET 和 POST 方法,仍然显示相同的错误

谁能帮我解决这个问题

谢谢

【问题讨论】:

  • 看起来&lt;form action="." 应该是&lt;form action="/App"
  • 谢谢先生,我也试过了,但是没用。

标签: python html flask


【解决方案1】:

首先,您的表单操作应该指向处理表单数据的视图(即/App):

<form action="/App" method="post">

其次,你应该只在请求的方法是POST时获取表单数据,因为你已经在模板中设置了method="post"。另外,当请求方法为GET时,您需要渲染包含表单的App.html:

@app.route('/App', methods=['POST', 'GET'])
def App():
    if request.method == 'POST':  # get form data when method is POST
        search = request.form['search']
        return render_template('output.html', n=search)
    return render_template('App.html')  # when the method is GET, it will render App.html 

附:您得到的错误解释清楚,表单数据中没有名为search 的键。

【讨论】:

  • 不客气,如果你觉得这个回答有用,请采纳。
猜你喜欢
  • 1970-01-01
  • 2018-12-20
  • 2020-10-17
  • 2018-06-21
  • 2021-07-04
  • 2020-07-10
  • 2018-12-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多