我正在尝试使用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代码。它甚至无法创建对象。
答案 0 :(得分:0)
import requests
import json
header = {
"Content-Type" : "application/json",
"Accept":"application/json"
}
您需要使用json.dumps
将字典转换为正确的格式,并且需要使用request.post
代替delete
request_url = 'YOUR_END_POINT'
data = json.dumps(data)
response = requests.post(url=request_url,data=data,headers=headers)
我认为应该解决它。