400错误的请求:无法解码JSON对象; PUT请求(烧瓶)

时间:2020-04-28 03:59:53

标签: python flask flask-restful

尝试将JSON有效负载测试为PUT请求时,出现以下错误。我不确定是我的测试导致错误还是其他原因导致了错误?如果我将该行注释掉,HTTP动词将正确响应。

werkzeug.exceptions.BadRequest: 
400 Bad Request: Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)
-> args = self.put_request_parser.parse_args()

在调试时,这里是调用parse_args()时实际发送的内容。我不确定在这种情况下为什么unparsed_arguments是空字典?

EnvironHeaders([('User-Agent', 'werkzeug/0.14.1'), ('Host', 'localhost'), 
('Content-Type', 'application/json'), ('Content-Length', '0'), 
('Authorization', 'Bearer <token>')]), 
'url': 'http://localhost/api/v1/todos/3', 'unparsed_arguments': {}}

tests.py

class TestUpdateTodoResource(ApiTestCase):
    '''Verify that a client succesfully updates an existing todo.'''

    def test_put_update_user_todo(self):
        with app.test_client() as client:
            http_response = client.put(
                "api/v1/todos/3",
                headers={
                    'content-type': 'application/json',
                    'authorization': f"Bearer {token}"
                },
                data = {
                    "name": "Never do this todo!"
                }
            )
        self.assertEqual(http_response.status_code, 204)

todos.py

class ApiTodo(Resource):

    put_request_parser = reqparse.RequestParser()
    put_request_parser.add_argument(
        'name',
        required=True,
        location=['form', 'json'],
        help="Cannot accept a blank description"
    )

    @auth.login_required
    def put(self, id):
        try:
            user_todo = Todo.select().join(User).where(
                (Todo.id == id) & (User.id == g.user.id)
            ).get()
        except Todo.DoesNotExist:
            abort(404, description="That todo no longer exists")
        args = self.put_request_parser.parse_args()
        if not args['name']:
            abort(400, description="Must provide a todo description")
        updated_todo = user_todo.update(**args)
        updated_todo.execute()
        return marshal(set_todo_creator(updated_todo), todo_fields, 'todo'), 204

0 个答案:

没有答案