问题:
使用python requests
和chrome的邮递员时的响应对于同一请求不一致。
需要注意的事项:
1)网址是https。
2)json是请求和响应的数据格式
3)python版本3.x.
4)requests
版本2.2
python代码:
headers = {'Content-Type': 'application/json'}
response = requests.post(self.__url, data=jsonpickle.encode(apiContractObject), headers=headers, verify=True)
print(response.text)
python代码中的响应
{
"productId": 0,
"productName": "testingPy",
"yearsArray": [
{
"key": 0,
"value": {
"outgo": 100.0,
"benefit": 0.0,
"net": -100.0,
"year": "2017-2018",
"age": 0
}
}
]
}
邮递员对同一请求的回复
{
"productId": 0,
"productName": "testingPy",
"yearsArray": [
{
"key": 0,
"value": {
"outgo": 100,
"benefit": 0,
"net": -100,
"year": "2017-2018",
"age": 0
}
},
{
"key": 1,
"value": {
"outgo": 0,
"benefit": 110.39,
"net": 110.39,
"year": "2018-2019",
"age": 1
}
}
]
}
差异
yearsArray
在python代码的响应中有1个元素但实际上应该有2个,如postman响应中所示
我是Python的新手!
编辑:
apiContractObject
是这个python类:
class FDCashflowContract:
"""Contract object for API"""
def __init__(self):
self.projectionType = 0
self.isCumulative = 0
self.dateOfDeposit = ''
self.depositHolderDob = ''
self.depositDuration = DepositDuration(0, 0, 0)
self.depositAmount = 0
self.compoundingFrequency = 0
self.interestPayOutFrequency = 0
self.interestRate = 0,
self.doYouKnowMaturityAmount = True
self.maturityAmount = 0
self.doYouKnowInterestPayOutAmount = True
self.interestPayOutAmount = 0
self.firstInterestPayOutDate = ''
self.productName = 'testingPy'
class DepositDuration:
"""A class that represents the duration object for use as a contract object"""
def __init__(self, years, months, days):
self._years = years
self._months = months
self._days = days
但传递的实例是:
duration = finfloApiModel.DepositDuration(1, 0, 0)
contract = finfloApiModel.FDCashflowContract()
contract.depositAmount = 100
contract.depositDuration = duration
contract.interestRate = 10
contract.dateOfDeposit = '05-12-2017'
contract.depositHolderDob = '04-27-2017'
contract.isCumulative = 1
contract.projectionType = 1
这是邮递员的要求:
{
"productId": 0,
"projectionType": 1,
"productName": "testingPy",
"isCumulative": 1,
"dateOfDeposit": "2017-05-12T06:26:45.239Z",
"depositHolderDob": "2017-05-12T06:26:45.239Z",
"depositDuration": {
"years": 1,
"months": 0,
"days": 0
},
"depositAmount": 100,
"compoundingFrequency": 0,
"interestPayOutFrequency": 0,
"interestRate": 10,
"doYouKnowMaturityAmount": false,
"maturityAmount": 0,
"doYouKnowInterestPayOutAmount": false,
"interestPayOutAmount": 0
}
答案 0 :(得分:0)
从根本上:问题是@Ray& @mohammed建议是请求。 REST服务是在ASP.NET Web API 2平台上编写的,REST控制器上的模型绑定器期望请求对象(JSON)与预期作为输入的模型具有完全相同的结构和拼写。
发现问题:Python请求中的问题是DepositDuration
对象的属性Years
,Months
和Days
之前是_
并且没有绑定,并且在api上默认为零,正确地响应了适当的响应。
class DepositDuration:
"""A class that represents the duration object for use as a contract object"""
def __init__(self, years, months, days):
self._years = years
self._months = months
self._days = days
解决方案:我已从python类DepositDuration的属性_
,years
和{{1}中删除months
一切都有效!
days