【问题标题】:RequestParser: Cannot Parse Dictionary ArgumentRequestParser:无法解析字典参数
【发布时间】:2021-04-22 02:38:55
【问题描述】:

当尝试将字典对象传递到请求中时,RequestParser 会引发 400 错误,并使用 {error_msg}" 返回以下错误:

字典更新序列元素#0的长度为1; 2 是必需的

我试图解析参数的方式如下:

patch_parser = reqparse.RequestParser()
# ...
patch_parser.add_argument("labels", type=dict, help="{error_msg}", store_missing=False)

# some POST/PUT request function
@app.route('/path/<id:int>')
def someFunction():
  args = patch_parser.parse_args()
  # ...

发出请求的代码:

toUpdateWith = {"name": "Test", "description": "This is a test."}
toUpdateWith['labels'] = { "4" : "create"}
response = self.conn.post('/path/2', data=toUpdateWith)

传入的数据是:

{
  "name": "Test",
  "description": "This is a test.",
  "labels": { 
    "4": "create"
  }
}

虽然通过 Postman 可以正常工作,但以编程方式执行此操作时不起作用。那么,究竟为什么会出现这个错误呢?

如果有任何我遗漏的信息,请告诉我。

【问题讨论】:

    标签: python flask flask-restful


    【解决方案1】:

    如果您想要一个带有字典的参数,则需要改为通过 json 传递数据。

    toUpdateWith = {"name": "Test", "description": "This is a test."}
    toUpdateWith['labels'] = { "4" : "create"}
    response = self.conn.post('/path/2', json=toUpdateWith)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-15
      • 1970-01-01
      • 2014-07-04
      • 1970-01-01
      相关资源
      最近更新 更多