【问题标题】:Flask-Restful Error: request Content-Type was not 'application/json'."}Flask-Restful 错误:请求 Content-Type 不是 \'application/json\'。\"}
【发布时间】:2022-11-11 02:30:57
【问题描述】:

我关注了this tutorial,进展顺利。然后他介绍了reqparse,我也跟着去了。我试图测试我的代码,我得到了这个错误 {'message': "Did not attempt to load JSON data because the request Content-Type was not 'application/json'."}

我不知道我是否遗漏了一些非常明显的东西,但我很确定我完全复制了他的代码。这是代码: main.py

from flask import Flask, request
from flask_restful import Api, Resource, reqparse

app = Flask(__name__)
api = Api(app)

#basic get and post
names = {"sai": {"age": 19, "gender": "male"},
            "bill": {"age": 23, "gender": "male"}}
class HelloWorld(Resource):
    def get(self, name, numb):
        return names[name]

    def post(self):
        return {"data": "Posted"}

api.add_resource(HelloWorld, "/helloworld/<string:name>/<int:numb>")

# getting larger data
pictures = {}
class picture(Resource):
    def get(self, picture_id):
        return pictures[picture_id]

    def put(self, picture_id):
        print(request.form['likes'])
        pass

api.add_resource(picture, "/picture/<int:picture_id>")

# reqparse
video_put_args = reqparse.RequestParser() # make new request parser object to make sure it fits the correct guidelines
video_put_args.add_argument("name", type=str, help="Name of the video")
video_put_args.add_argument("views", type=int, help="Views on the video")
video_put_args.add_argument("likes", type=int, help="Likes on the video")

videos = {}

class Video(Resource):
    def get(self, video_id):
        return videos[video_id]

    def post(self, video_id):
        args = video_put_args.parse_args()
        print(request.form['likes'])
        return {video_id: args}

api.add_resource(Video, "/video/<int:video_id>")

if __name__ == "__main__":
    app.run(debug=True)

test_rest.py

import requests

BASE = "http://127.0.0.1:5000/"

response = requests.post(BASE + 'video/1', {"likes": 10})

print(response.json())

【问题讨论】:

    标签: python rest flask flask-restful


    【解决方案1】:

    我不知道你为什么有问题,据我所知,你确实复制了他的做法。这是一个可行的修复程序,尽管我无法解释为什么他的代码有效而您的代码无效。他的视频已有两年历史,因此可能是不推荐使用的行为。

    import requests
    import json
    
    BASE = "http://127.0.0.1:5000/"
    
    payload = {"likes": 10}
    
    headers = {'accept': 'application/json'}
    response = requests.post(BASE + 'video/1', json=payload)
    
    print(response.json())
    

    【讨论】:

      【解决方案2】:

      您可以像错误消息中所说的那样设置标题。

      import requests, json
      
      BASE = "http://127.0.0.1:5000/"
      # Set request's header.
      headers = {"Content-Type": "application/json; charset=utf-8"}
      # Set data.
      data = {"likes": 10}
      # 
      response = requests.post(BASE + 'video/1', headers=headers, json=data)
      
      print("Status Code: ", response.status_code)
      print("JSON Response: ", response.json())
      

      【讨论】:

        【解决方案3】:

        目前遵循相同的教程并面临相同的问题。 通过为数据添加关键字参数json 解决了我的问题

        response = requests.post(BASE + 'video/1', json={"likes": 10})
        

        【讨论】:

          【解决方案4】:

          如果您能够更改代码

          我设法通过将location=&lt;target&gt; 添加到parser.add_argument() 函数来解决这个问题。

            parser.add_argument("email", type=str, required=True)
          + parser.add_argument("email", type=str, required=True, location='form')
          

          您需要添加输入数据的正确位置。一些可能的值为jsonargsform。了解更多信息: https://flask-restful.readthedocs.io/en/latest/api.html#reqparse.RequestParser.parse_args

          就我而言,它是form。因为我使用multipart/form-data 作为输入。

          如果您无法更改代码

          werkzeug降级到this commit之前的版本

          信用:Flask-restx request parser returns 400 Bad Request

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2015-10-20
            • 1970-01-01
            • 2011-08-11
            • 1970-01-01
            • 2020-04-23
            • 1970-01-01
            • 1970-01-01
            • 2022-12-01
            相关资源
            最近更新 更多