首页 > 解决方案 > 如何将python类(嵌套)编码为json并使用post请求发送?

问题描述

我正在使用 python 将我的类编码为JSON,但是当我提出PUT请求时,引发错误说: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)。

标签: pythonjsonpython-requests

解决方案


推荐阅读