flask/post+jsonschema报错:None is not of type 'object'
用python的unittest,对flask的post测试,testcase如下:
[jenkins_bot@A04-R08-I53-67 testChecking]$ python test_testCheckingService.py
...WARNING: input json is invalid: (None is not of type 'object'
Failed validating 'type' in schema:
{'description': 'POST request coming in test service API',
'properties': {'note': {'description': 'The note for the operation',
'type': 'string'},
...详细的jsonschema定义省略...
'title': 'test service API request',
'type': 'object'}
On instance:
None)
F...............
这可以理解,因为用了jsonschema校验传入的json格式。
但是报这个错就很困扰了,从字面上来看是说指定的'type'为'object',但是接收到的是空,所以jsonschema验证失败。
可是分明是传了data过去的,而且也转成json格式了的!
于是又试了下避免传数据,直接用get模式:
看来问题还是出在post传入的数据上。
于是又查了flask的文档,也没找到什么帮助信息。
最后还是放狗搜到了一个开发bug:https://github.com/noirbizarre/flask-restplus/issues/209
于是按照所说的,在调用app.post时指定content-type:
反思:直接原因如209这个bug所说,是报错信息不友好。更深层次的原因则在于,图省事方便,没有直接用python写服务器端的程序,而是直接用了现成的flask模块框架,而且比较盲目地信赖了flask的jsonify会自己处理请求头的json格式指定。方便倒是很方便,但像这样出错了之后,就不好找了问题了...
def test_post_new_testCheckingService(self): rsp = self.app.post('/test', data=json.dumps(json_new)).data data = json.loads(rsp) self.assertEquals(1, data['return_code'])但是报错:
[jenkins_bot@A04-R08-I53-67 testChecking]$ python test_testCheckingService.py
...WARNING: input json is invalid: (None is not of type 'object'
Failed validating 'type' in schema:
{'description': 'POST request coming in test service API',
'properties': {'note': {'description': 'The note for the operation',
'type': 'string'},
...详细的jsonschema定义省略...
'title': 'test service API request',
'type': 'object'}
On instance:
None)
F...............
这可以理解,因为用了jsonschema校验传入的json格式。
但是报这个错就很困扰了,从字面上来看是说指定的'type'为'object',但是接收到的是空,所以jsonschema验证失败。
可是分明是传了data过去的,而且也转成json格式了的!
data=json.dumps(json_new)
反复检查了预定义的dict()格式的数据json_new,以及jsonschema的用法,确认没有问题。于是又试了下避免传数据,直接用get模式:
def test_get_about(self): rsp = self.app.get('/help') self.assertIn('OK', rsp.data)没问题!
看来问题还是出在post传入的数据上。
于是又查了flask的文档,也没找到什么帮助信息。
最后还是放狗搜到了一个开发bug:https://github.com/noirbizarre/flask-restplus/issues/209
于是按照所说的,在调用app.post时指定content-type:
self.app.post('/test', data=json.dumps(json_new), headers={'content-type': 'application/json'})执行,问题解决
反思:直接原因如209这个bug所说,是报错信息不友好。更深层次的原因则在于,图省事方便,没有直接用python写服务器端的程序,而是直接用了现成的flask模块框架,而且比较盲目地信赖了flask的jsonify会自己处理请求头的json格式指定。方便倒是很方便,但像这样出错了之后,就不好找了问题了...
评论
发表评论