You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask中PUT方法无法正常工作的问题求助

Flask PUT请求报错的解决方法

问题描述

执行PUT请求命令:

curl http://127.0.0.1:5000/videos/video3 -d "title=YES" -X PUT

返回错误:

{"message": "The browser (or proxy) sent a request that this server could not understand."}

GET方法正常运行,目标是成功创建/更新video3的title为YES,返回包含三个视频的结果。

报错原因

使用curl -d发送PUT请求时,curl不会自动设置Content-Type: application/x-www-form-urlencoded请求头,而Flask-RESTful的reqparse默认需要明确的Content-Type来解析表单数据,导致服务器无法识别请求格式。

解决方案

方案1:修改curl命令,显式指定Content-Type

调整curl命令,添加Content-Type请求头:

curl http://127.0.0.1:5000/videos/video3 -d "title=YES" -H "Content-Type: application/x-www-form-urlencoded" -X PUT

方案2:改用JSON格式发送请求(推荐RESTful风格)

步骤1:修改curl命令为JSON格式

curl http://127.0.0.1:5000/videos/video3 -H "Content-Type: application/json" -d '{"title": "YES"}' -X PUT

步骤2:调整代码中的解析器,支持JSON数据

修改reqparse的参数,添加location=['form', 'json'],让解析器同时支持表单和JSON数据:

parser = reqparse.RequestParser()
parser.add_argument('title', required=True, location=['form', 'json'])

验证结果

执行正确的PUT命令后,发送GET请求查看所有视频:

curl http://127.0.0.1:5000/videos/all

将返回期望结果:

{"video1": {"title": "Hello World in Python"}, "video2": {"title": "Why Matlab is the Best Language Ever"}, "video3": {"title": "YES"}}

内容的提问来源于stack exchange,提问作者BSR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 19:50:17