Skip to main content
 首页 » 编程设计

python之Django POST curl REST API

2024年11月01日31jillzhang

我想通过使用 POST 的 django 调用 RESTful api。我知道如何执行 GET,但我如何执行 POST?

对于 get,我使用 requests.get(...)

API 调用是:

curl -v -X POST -H "Content-Type: application/json" \ 
     -H "Accept: application/json" \ 
     -X POST \ 
     --user user:password \ 
     https://this.is.an.external.domain \ 
     -d "{\"name\": \"Marcus0.1\",\"start\": 500000,\"end\": 1361640526000}" 

更新

所以,我找到了requests.post,但是如何翻译上面的curl命令

请您参考如下方法:

转换为 Python 请求调用的 curl 命令将是:

# construct a python dictionary to serialize to JSON later 
item = { "name": "Marcus0.1", "start": 500000, "end": 1361640526000 } 
 
resp = requests.post("https://this.is.an.external.domain",  
              data=json.dumps(item),  # serialize the dictionary from above into json 
              headers={ 
                       "Content-Type":"application/json", 
                       "Accept": "application/json" 
                      }) 
 
print resp.status_code 
print resp.content