2017-12-15 5 views
1

파이썬을 사용하여 요청을하려고합니다. API는 다음을 사용합니다.파이썬을 사용한 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' 

새 센서를 만드는 데 사용됩니다. 나는 파이썬으로 일을하려고하지, 그리고 난 개념의 증거를 만들었습니다

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) 

는 제대로 작동하지만 파이썬 코드와 아무. 객체 생성에도 실패합니다.

+1

정말 좋지는 않지만 최근에는'data = data'보다는 POST에서'json = data'를 사용해야하는 문제가있었습니다. – orangeInk

+0

어떻게 실패합니까? 흔적이 뭐야? –

+0

json 사용하기 작동하지만 온도를 50으로 변경할 수 없습니다. –

답변

0
import requests 
import json 

header = { 
"Content-Type" : "application/json", 
"Accept":"application/json" 
} 

당신은 내가 그 그것을 해결해야한다고 생각 json.dumps를 사용하여 적절한 형식으로 사전을 변환하는 대신 delete

request_url = 'YOUR_END_POINT' 
data = json.dumps(data) 
response = requests.post(url=request_url,data=data,headers=headers) 

request.post를 사용해야합니다.