Flask PUT请求报错排查:Content-Type与405方法不允许问题
问题分析与解决
1. 第二个curl命令的语法错误(导致405 METHOD NOT ALLOWED)
你修改后的curl命令里-X -PUT是错误写法,-X参数后需直接跟HTTP方法,不能额外加横杠,正确格式应为-X PUT或--request PUT。这个语法错误导致curl实际发送的请求方法不符合预期,服务器因此返回405不允许的方法。
2. Flask-RESTful的RequestParser未配置接收JSON数据
默认情况下,reqparse.RequestParser()只会解析表单格式的请求数据,无法读取JSON格式的请求体。即使你设置了Content-Type: application/json,parser也无法获取到title参数,后续会触发参数缺失的错误。需要在添加参数时指定location='json',让parser支持解析JSON数据。
修正后的代码与curl命令
修正后的App.py代码
from flask import Flask from flask_restful import Resource, Api, reqparse app = Flask("VideoAPI") api = Api(app) # 添加location='json',让parser能读取JSON格式的请求参数 parser = reqparse.RequestParser() parser.add_argument('title', required=True, location='json') videos = { 'video1' : {'title':'Hello world in python'}, 'video2' : {'title':'Why R is good'} } class Video(Resource): def get(self, video_id): if video_id=="all": return videos return videos[video_id] def put(self, video_id): args = parser.parse_args() new_video = {'title': args['title']} videos[video_id] = new_video return {video_id: videos[video_id]}, 201 api.add_resource(Video, '/videos/<video_id>') if __name__=='__main__': app.run(debug=True) # 开启debug便于查看详细日志
正确的curl命令
curl -i -X PUT -H "Content-Type: application/json" -d '{"title":"My New Video"}' http://localhost:5000/videos/video3
补充说明
- 第一个原始curl命令的问题:
-d "title"="My New Video"格式错误,表单格式应写为-d "title=My New Video",此时无需设置JSON类型的Content-Type,但RESTful API通常推荐使用JSON格式交互。 - 开启
debug=True后,控制台会输出详细的请求日志,能更快定位参数解析、路由匹配等问题。
内容的提问来源于stack exchange,提问作者brins
相关产品推荐
相关产品推荐

