【问题标题】:API requests using python使用 python 的 API 请求
【发布时间】: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


【解决方案1】:
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)

我认为应该可以解决它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-29
    • 1970-01-01
    • 2022-10-12
    • 1970-01-01
    • 2018-07-13
    • 2013-06-22
    相关资源
    最近更新 更多