Python запрашивает пост-методы противоречивые результаты

Проблема: Ответ при использовании Python requests и почтальон Chrome не согласуются с тем же запросом.

На что следует обратить внимание: 1) URL-адрес на 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 имеет 1 элемент в ответе кода Python, но фактически должен иметь 2, как видно из ответа почтальона

Я новичок в 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
}

1 ответ

Принципиально: проблема, предложенная @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

Решение: я удалил _ из атрибутов DepositDuration класса Python years, months а также days и вуаля все работает!

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
Другие вопросы по тегам