【发布时间】:2017-12-15 08:02:09
【问题描述】:
我正在尝试使用 python 发出请求。 API 使用:
curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{ \
"$class": "org.acme.model.sensor", \
"sensorId": "1", \
"type": "Temperature", \
"value": "10", \
"timestamp": 1234123 \
}' 'http://localhost:3000/api/sensor'
创建一个新的传感器。我正在尝试用 python 来做这件事,并且我已经创建了概念证明:
data = {
"$class": "org.acme.model.sensor",
"sensorId": "", #change in the loop with i
"type": "Temperature",
"value": "10",
"timestamp": 382453824
}
header = {
"Content-Type" : "application/json",
"Accept":"application/json"
}
url = "http://localhost:3000/api/sensor"
for i in range(2):
data["sensorId"]=str(i+1)
response = requests.post(url, data=data, headers=header)
#Now I modify the data
data["Temperature"]="50"
response = requests.put(url, data=data, headers=header)
现在,擦除:
for i in range(2):
url="http://localhost:3000/api/sensor/"+str(i+1)
response = requests.delete(url)
使用 curl,它可以正常工作,但不能使用 python 代码。它甚至无法创建对象。
【问题讨论】:
-
我真的不擅长这个,但我最近遇到了一个问题,我不得不在 POST 中使用
json=data而不是data=data。 -
它是如何失败的? Traceback 是什么?
-
使用 json 可以,但我无法将温度更改为 50
-
“不工作”不是对您的问题的有用描述。请解释您得到的结果(包括确切的错误消息和完整的回溯,如果您有异常)。
-
它解决了,我得到了一个404错误,我是因为服务器sintaxis做出“放”谢谢大家
标签: python api curl python-requests