我想用Django使用POST调用RESTful api。我知道如何进行GET,但是如何进行POST?

为了得到,我使用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命令

最佳答案

将curl命令转换为Python Requests调用将是:

# 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

关于python - Django POST curl REST API,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18086291/

10-16 07:05