2013-08-06 148 views
2

我想用django調用一個使用POST的RESTful api。我知道如何做GET,但我該如何做POST?Django POST curl REST api

對於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命令

+0

看起來像你的問題已經回答了(在這個問題)這裏:http://stackoverflow.com/questions/9958039/using-python-requests-library –

+0

這有什麼好做的Django。這是一個關於'請求'的基本問題。 – vad

回答

2

將curl命令轉換爲Python請求調用將是:

# 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 
+1

我想你錯過了身份驗證。 =) – Lukasa