【发布时间】:2022-01-02 05:01:33
【问题描述】:
我正在尝试运行我的第一个烧瓶应用程序,但在 Postman 上发送 POST 请求后出现以下错误。
错误: werkzeug.exceptions.BadRequestKeyError:400 错误请求:浏览器(或代理)发送了此服务器无法理解的请求。 KeyError: '目标'
错误可能来自这里:goal = request.form['goal'] ,我已经尝试将request.form 更改为request.json或form.get,但没有成功。 :(
有什么想法吗?
注意:我使用的是 Windows、Visual Studio、Python 3.9 和 Postman。
app = Flask(__name__)
@app.route('/create', methods=('GET', 'POST'))
def create():
if request.method == 'POST':
goal = request.form['goal']
content = request.form.get['content']
if not title:
flash('Goal is required!')
return calc(goal,content)
if __name__ == "__main__":
app.run(debug=True)
def calc(goal, content):
#rest of the code here...#
return jsonify({
"status": 200,
"message": "Success",
"data":data
})```
【问题讨论】:
-
我发现在这种情况下,在
create()函数的开头添加 print(request) 非常有用。这应该会向您展示对象中有哪些元素,并帮助您确定下一个调试步骤。 -
感谢 @JamesMcPherson 的输入,我在 create() 函数之后添加了以下几行:
print(request.method) print(request.url) print(request.data) print(request.headers)打印结果为:POST 127.0.0.1:5000/create b'' None User-Agent : PostmanRuntime/7.28.4 Accept: */* Postman-Token: 4c3a-896f-yy8b-a82c-dxxx8c9xx (edited) Host: 127.0.0.1:5000 Accept-Encoding: gzip, deflate, br Connection: keep-alive Content- Length: 0 作为 request.data "b''" 和 Content-Length: 0 我假设我需要调整应用程序才能正确接收 POST 信息。 -
在我看来,您尚未创建包含表单元素的初始基本网页 (index.html)。如果您查看github.com/jmcp/find-my-electorate/blob/master/app.py#L271,您会看到基本路由调用
render_template()并带有一个参数,即github.com/jmcp/find-my-electorate/blob/master/templates/…。这将创建一个传递给 POST 方法的 -
感谢@JamesMcPherson 的帮助,我在创建初始基本网页后能够收到 POST 信息!我正在尝试接受答案,但我不确定为什么答案/评论旁边没有显示复选标记。
-
可能是因为它是评论而不是答案。我会马上解决的。谢谢你
标签: python json flask werkzeug