2013-01-31 44 views
2

一個簡單的API我有一個簡單的API端點:訪問與Python

http://example.de/create.json 

我需要發送通過POST如下:

-text

-url

- 用戶名

此任務的curl命令如下所示:

curl --data-urlencode "text=Beispieltext" -d "url=http://google.de" -d "username=User1" http://example.de/create.json 

我想在我的代碼中實現這個。我想將數據提交給API,並使用API​​的答案。 其實我不知道從哪裏開始。我讀了很多關於Pycurl,urllib2和subprocess的書,但現在我什麼都不懂了:D

你會怎麼做? 我需要幫助,我不知道從哪裏開始!

+0

[要求](http://docs.python-requests.org/en/latest/)是我最喜歡的捲曲狀的通話 –

+0

@AlexL庫我會試一試。謝謝! –

回答

1

很簡單。應該是這樣的:

import pycurl 
import StringIO 

c = pycurl.Curl() 
c.setopt(c.URL, 'http://example.de/create.json') 
output = StringIO.StringIO() 
c.setopt(c.WRITEFUNCTION, output.write) 
c.setopt(c.POSTFIELDS, 'your post data') 
c.perform() 

結果在output.getvalue()中。完成後不要忘記output.close()。

+0

如何定義我的發佈數據? 例如c.setopt(c.POSTFIELDS,'text ='+ mytext)不起作用! 如何在其中使用變量? –

+0

不存在「不起作用」的錯誤 – stark

+0

嘗試urllib.urlencode(「text = Beispieltext」) – stark

0

的libcurl Examples(看到那些從右側科拉姆)