python restful接口返回类型出错_【基本解决】Flask-Restful的api当不满足条件时返回自定义信息...

之前用Flask-restful的api时,用代码:class SmsCodeAPI(Resource):

def __init__(self):

self.reqparse = reqparse.RequestParser()

self.reqparse.add_argument(‘phone’,

type = str,

location = ‘json’)

self.reqparse.add_argument(‘type’,

type = str,

required=True,

help=’No type provided for get sms code’,

location = ‘json’)

super(SmsCodeAPI, self).__init__()

去访问时,缺少type参数时:

返回的是:{

"message": {

"type": "No type provided for get sms code"

}

}

现在想要实现:

可以返回统一的格式,类似于正常的返回时的:

带code,message,xxx{

"code":200,

"message":"OK",

"smscode":"489348"

}

的格式

此处希望是:{

"code": 100001,

"message": "No type provided for get sms code",

}

flask-restful api required parameter return custom json

->

可以自己实现对应的函数,返回特定的json字符串。

但是不是此处的,重写reqired参数不满足要求的错误。

flask-restful custom  add_argument required error

感觉还是需要自己去重写了。

flask-restful custom error

虽然此处已经通过代码,自定义要返回的json了:@api.representation(‘application/json’)

def output_json(data, code, headers=None):

gLog.debug("data=%s, code=%s, headers=%s", data, code, headers)

resp = make_response(json.dumps(data), code)

gLog.debug("resp=%s", resp)

resp.headers.extend(headers or {})

gLog.debug("resp.headers=%s", resp.headers)

return resp

并且当模拟缺少type参数时的错误是400:[2016-10-08 19:44:22,076 DEBUG __init__.py:69 output_json] data={‘message’: {‘type’: ‘No type provided for get sms code’}}, code=400, headers=Content-Type: text/html

[2016-10-08 19:44:22,080 DEBUG __init__.py:71 output_json] resp=

[2016-10-08 19:44:22,081 DEBUG __init__.py:73 output_json] resp.headers=Content-Type: text/html; charset=utf-8

Content-Length: 58

但是,还是无法捕获,reqparse的add_argument的设置required=True时的错误异常。

RequestParser add_argument

RequestParser add_argument required

算了,还是自己去自定义吧。

最后用代码:class SmsCodeAPI(Resource):

def __init__(self):

self.reqparse = reqparse.RequestParser()

self.reqparse.add_argument(‘phone’,

type = str,

default = None,

location = ‘json’)

self.reqparse.add_argument(‘type’,

type = str,

default = None,

# required=True,

# help=’Type must be provided when get sms code’,

location = ‘json’)

super(SmsCodeAPI, self).__init__()

def post(self):

args = self.reqparse.parse_args()

gLog.debug("args=%s", args)

type = args[‘type’]

gLog.debug("type=%s", type)

if type is None:

respJsonDict = {

"code": 400,

"message": "Type must be provided when get sms code",

}

gLog.debug("respJsonDict=%s", respJsonDict)

return respJsonDict

在没有传入type参数时,输出:{

"code": 400,

"message": "Type must be provided when get sms code"

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值