我正在尝试通过REST API发布一些数据。但是,使用以下代码,该程序拒绝遵守(为提高可读性而添加了绒毛):
def Actions(self, imei, name):
global addAttribute
if addAttribute == True:
attributes = {"decoder.timezone":"Etc/GMT"}
else:
attributes = ""
url = "https://example.com/api/devices/"
data = {"name":name, "uniqueId":imei, "attributes":attributes}
print("data not transformed:")
print(data)
print()
data_json = json.dumps(data)
print("data transformed by json.dumps():")
print(data_json)
print()
test = requests.post(url, auth=('mylogin', 'pwd'), json=data_json)
print(test.content)
控制台说:
data not transformed:
{'name': 'Example 1', 'uniqueId': 'Example 1', 'attributes': {'decoder.timezone': 'Etc/GMT'}}
data transformed by json.dumps():
{"name": "Example 1", "uniqueId": "Example 1", "attributes": {"decoder.timezone": "Etc/GMT"}}
b'Cannot construct instance of `org.traccar.model.Device` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value (\'{"name": "Example 1", "uniqueId": "Example 1", "attributes": {"decoder.timezone": "Etc/GMT"}}\')\n at [Source: (org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream); line: 1, column: 1]'
也许我应该以不同的方式来表达我的数据,而不是作为字典来表达?如果可以,怎么办?
答案 0 :(得分:1)
根据requests
documentation,字段json
适用于dict
个对象,字段data
适用于string
个对象。
您正在string
字段中传递dict
。您可能需要执行以下操作:
data = {"name":name, "uniqueId":imei, "attributes":attributes}
data_json = json.dumps(data)
test = requests.post(url, auth=('mylogin', 'pwd'), data=data_json)
print(test.content)
或类似的内容:
data = {"name":name, "uniqueId":imei, "attributes":attributes}
test = requests.post(url, auth=('mylogin', 'pwd'), json=data)
print(test.content)
它们都应该起作用,但是您应该选择第二个,因为json.dump
操作是在发布请求中完成的。