如何将python类(嵌套)编码为json并使用post请求发送?

时间:2019-03-23 12:21:04

标签: python json python-requests

我正在使用python将类编码为JSON,但是当我发出PUT请求时,raiser错误会显示:bad request 400。但是我的JSON是有效的,所以我不确定为什么会发生此错误。

import json
import requests

class Temperature:
    def __init__(self, value, type):
        self.value = value
        self.type = type
    def reprJSON(self):
        return dict(value=self.value, type=self.type)

class Occupation:
    def __init__(self, value, type):
        self.value = value
        self.type = type
    def reprJSON(self):
        return dict(value=self.value, type=self.type)

class MaxCapacity:
    def __init__(self, value, type):
        self.value = value
        self.type = type
    def reprJSON(self):
        return dict(value=self.value, type=self.type)

class Room:
    def __init__(self, id, type):
        self.id = id
        self.type = type
        self.temperature = Temperature('30','Float')
        self.occupation = Occupation('0','Integer')
        self.maxcapacity = MaxCapacity('50','Integer')
    def reprJSON(self):
        return dict(id=self.id, type=self.type, temperature=self.temperature, occupation=self.occupation, maxcapacity=self.maxcapacity)

    def createRoom(self):
        print("Creating Entity...")
        url = 'http://localhost:1026/v2/entities'
        headers = {'Content-Type': 'application/json'}
        payload = json.dumps(self.reprJSON(), cls=ComplexEncoder)
        print(payload)
        r = requests.post(url,json=payload)
        print(r.raise_for_status()) # status for debugging
        print(r.status_code)
        print("Entity Created successfully!")



class ComplexEncoder(json.JSONEncoder):
    def default(self, obj):
        if hasattr(obj,'reprJSON'):
            return obj.reprJSON()
        else:
            return json.JSONEncoder.default(self, obj)

if __name__ == '__main__':

    room = Room('urn:ngsi-ld:Room:001','Room')
    room.createRoom()
    #room.createRoom(url, headers)

实际上,我收到此错误:

raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: http://localhost:1026/v2/entities

我希望POST成功返回(代码201)。

0 个答案:

没有答案