【问题标题】:Flask rest plus Parser does not seem to work with postFlask restplus Parser 似乎不适用于 post
【发布时间】:2018-09-28 23:27:51
【问题描述】:

我已经在代码端点下面编写了从前端接收到的数据,我已经实现了相同的获取方式,它可以工作,但不能用于发布

parser = reqparse.RequestParser()
parser.add_argument("update", type=bool, help="Update the data set") 
parser.add_argument(
"set_name", type=str, help="Name of the set you want to add

@api.route("/add_set")
 class AddNewSet(Resource): 
@api.doc(parser=parser) 
def post(self):
     """ endpoint that handles request for deploying services 
         :return: (int) deployed service id from database. 
     """

          print "Hello hellooo"
          args = parser.parse_args() 
          print "doink"

抛出错误:

{ "message": "无法解码 JSON 对象:无法解码 JSON 对象" }

并且文本“doink”没有被打印,所以我怀疑parser.parse_args() 没有按预期工作,我相信或者我做错了什么。

【问题讨论】:

  • 你在发什么?删除 @api.doc(parser=parser) 后会发生什么?
  • 如果我删除 @api.doc(parser=parser) 然后我希望获取的参数不会出现在招摇文档中
  • @Ciastopiekarz 您必须将 location 设置为参数。解析器不知道参数在哪里(formjsonheaders 等)
  • 您可以查看this answer - 我认为 - 解决了您的问题。

标签: python flask flask-restplus


【解决方案1】:

默认情况下,RequestParser 从 request.json 和 request.values 中查找 args

请看:https://flask-restplus.readthedocs.io/en/stable/parsing.html#argument-locations

至于你的代码,我没有尝试你的方式来定义帖子的参数,我这样做

@api.expect(api.model(
  'ModelName', dict(
    arg1 = fields.String(required=True),
    arg2 = fields.Integer,
  )
))
def post(self):
  return {'result': 'success'}

我也建议给出明确的return 子句,甚至return None

【讨论】:

    猜你喜欢
    • 2011-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    • 2017-01-25
    • 2020-04-04
    • 2023-04-06
    相关资源
    最近更新 更多