python - 如何将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)。
解决方案
推荐阅读
- ruby - 为什么在 VS Code Terminal 中执行时 IRB 不显示输出?
- amazon-web-services - 来自 aws S3 的字节范围请求
- asp.net-core - 如何在我的项目中实现忘记密码链接?
- python - 熊猫过滤掉一列
- python - VIDIOC_QBUF:无效参数 V4l2 MEMORY USERPTR python 实现
- wordpress - 用不同的偏移量在不同的循环中查询不同的类别
- windows-10 - 永久设置 audiodg.exe 优先级和从属关系
- python - Python pygame在排序功能后不会重绘
- azure - 根据文件名限制 Azure FileShare 中的文件创建
- python - 线程在 python flask/uwsgi/nginx 发布请求中被杀死-正确的超时设置?