尝试使用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方法的工作,并认为我越来越接近与PUT方法,但现在卡住了。
from flask import Flask
from flask_restful import Resource, Api, reqparse, abort
app = Flask("VideoAPI")
api = Api(app)
parser = reqparse.RequestParser()
parser.add_argument('title',required=True)
videos = {
'video1': {'title': 'Hello World in Python'},
'video2': {'title': 'Why Matlab is the Best Language Ever'}
}
class Video(Resource):
def get(self, video_id):
if video_id == "all":
return videos
if video_id not in videos:
abort(404, message=f"Video {video_id} not found")
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()
预期输出:{"video1": {"title": "Hello World In Python"}, "video2": {"title": Why Matlab is the best language ever"}, "video3": {"title": "YES"}}
2条答案
按热度按时间t5fffqht1#
由于您没有在请求中指定Content-Type头,
curl
默认将其作为application/x-www-form-urlencoded
发送。因此,如果您将location='form'
添加到参数定义中,它应该可以正常工作:ozxc1zmp2#
您的put方法需要JSON格式
{"title": "YES"}
,但您发送的数据不是该格式。curl 请求应为
回应
要获得预期输出