猎鹰引发自定义异常json

时间:2019-03-14 09:14:39

标签: python falconframework

举起falcon.HTTPNotFound时,我会遵循JSON

 {
    "title": "404 Not Found",
    "description": {
        "message": "Model mymodel does not exist!",
        "model_id": "mymodel"
    }
}

但我想代替下面的内容发送

{
   "message": "Model mymodel does not exist!",
   "model_id": "mymodel"
}

我如何在Falcon中实现这一目标?

def expect_model_existence(req, resp, resource, params, require_exists):

    model_id = params['model_id']

    if require_exists and not Model.exists(model_id=model_id):
        response = {"message": f"Model {model_id} does not exist!", "model_id": model_id}
        raise falcon.HTTPNotFound(description=response)
    elif not require_exists and Model.exists(model_id=model_id):
        response = {"message": f"Model {model_id} already exists!", "model_id": model_id}
        raise falcon.HTTPConflict(description=response)

定义了一个检查模型是否存在的函数,并像以前一样应用

@falcon.before(expect_model_existence, True)
    def on_delete(self, req, resp, model_id):
       pass

0 个答案:

没有答案