python-3.x 培养瓶-无法使PUT方法工作?

a9wyjsp7  于 2023-02-17  发布在  Python
关注(0)|答案(2)|浏览(126)

尝试使用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"}}

t5fffqht

t5fffqht1#

由于您没有在请求中指定Content-Type头,curl默认将其作为application/x-www-form-urlencoded发送。因此,如果您将location='form'添加到参数定义中,它应该可以正常工作:

parser.add_argument('title', required=True, location='form')
ozxc1zmp

ozxc1zmp2#

您的put方法需要JSON格式{"title": "YES"},但您发送的数据不是该格式。
curl 请求应为

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

回应

{
    "video3": {
        "title": "YES"
    }
}

要获得预期输出

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
    return videos, 201

相关问题