Flask-restplus如何在没有身体的情况下发帖

时间:2015-11-06 03:51:08

标签: python flask flask-restplus

我想使用POST动词在带有flask-restplus的VM上执行操作,但是当没有正文时它总是会产生400.

VM_ACTION_FIELDS = {
      'vmActionId': fields.Integer(required=True, description='The vmActionId of the VmAction'),
      'vmId': fields.Integer(required=True, description='The vmId of the VmAction'),
      'status': fields.String(required=True, description='The status of the VmAction',
                              enum=['NEW', 'REQUESTED', 'IN_PROGRESS', 'ERROR', 'COMPLETED']),
      'actionType': fields.String(required=True, description='The actionType of the VmAction',
                                  enum=['STOP', 'RESTART']),
      'createdAt': fields.DateTime(required=True,
                                   description='The createdAt datetime of the VmAction'),
      'completedAt': fields.DateTime(required=True,
                                     description='The completedAt datetime of the VmAction'),
  }
  VM_ACTION_MODEL = api.model('VmAction', VM_ACTION_FIELDS)

  [snip]

      @vms_ns.route('/<int:vmId>/stop', endpoint='vmStop')
      class VmStopView(Resource):
          """
          Stop a VM
          """
          @api.marshal_with(VM_ACTION_MODEL, code=202)
          @api.doc(id='stopVm', description='Stop a Vm')
          def post(self, vmId):
              # do stuff 
              return vmAction, 202

结果是 400 {   “message”:“浏览器(或代理)发送了此服务器无法理解的请求。” }

如果我只是从post更改为get,它运行正常。但是,我真的想使用POST动词,因为这是我需要遵循的标准动词,用于自定义非CRUD动作。我是否已经将自己画在了一个带烧瓶的地方?

注意:对于需要正文的操作,它可以正常工作。它唯一的无体烧瓶 - restplus后操作,空体上有400个错误。

2 个答案:

答案 0 :(得分:0)

如果您将内容类型设置为application/json,我认为您的身体应至少为{}。 如果要提交空的有效负载,只需删除内容类型标题。

我认为这正是这个问题(我想弄清楚):https://github.com/noirbizarre/flask-restplus/issues/84

答案 1 :(得分:0)

这是一个解决方法,对我来说是阻止我,直到找到另一个解决方案:

@app.before_request
  def before_request():
      """This is a workaround to the bug described at
      https://github.com/noirbizarre/flask-restplus/issues/84"""
      ctlen = int(request.headers.environ.get('CONTENT_LENGTH', 0))
      if ctlen == 0:
          request.headers.environ['CONTENT_TYPE'] = None
相关问题