2009-11-05 53 views
3

下面是一些代碼被上傳文件:替代PycURL?

file_size = os.path.getsize('Tea.rdf') 
    f = file('Tea.rdf') 
    c = pycurl.Curl() 
    c.setopt(pycurl.URL, 'http://localhost:8080/openrdf-sesame/repositories/rep/statements') 
    c.setopt(pycurl.HTTPHEADER, ["Content-Type: application/rdf+xml;charset=UTF-8"]) 
    c.setopt(pycurl.PUT, 1) 
    c.setopt(pycurl.INFILE, f) 
    c.setopt(pycurl.INFILESIZE, file_size) 
    c.perform() 
    c.close() 

現在,我不是在所有喜歡這個PycURL經驗。你能提出其他的建議嗎?也許urllib2或httplib可以做同樣的事情?你能寫一些代碼顯示它嗎?

非常感謝!

+0

什麼問題? – gahooa 2009-11-05 19:58:26

+0

問題是,現在我試圖發佈一個查詢對這家商店...和捲曲給了我很多麻煩。所以,我只是想知道是否有另一種方式來做到這一點。 再次感謝 – pns 2009-11-05 20:26:42

回答

1

使用httplib2

import httplib2 
http = httplib2.Http() 

f = open('Tea.rdf') 
body = f.read() 
url = 'http://localhost:8080/openrdf-sesame/repositories/rep/statements' 
headers = {'Content-type': 'application/rdf+xml;charset=utf-8'} 
resp, content = http.request(url, 'PUT', body=body, headers=headers) 
# resp will contain headers and status, content the response body 
0

你的榜樣轉化爲httplib的:

import httplib 

host = 'localhost:8080' 
path = '/openrdf-sesame/repositories/rep/statements' 
path = '/index.html' 
headers = {'Content-type': 'application/rdf+xml;charset=utf-8'} 

f = open('Tea.rdf') 
conn = httplib.HTTPConnection(host) 
conn.request('PUT', path, f, headers) 
res = conn.getresponse() 
print res.status, res.reason 
print res.read() 
4

是,pycurl有一個不好的API設計,嫋嫋是強大的。它有更多的未來,然後urllib/urllib2。

也許你想嘗試使用human_curl。這是蟒蛇捲曲包裝。您可以通過來源https://github.com/lispython/human_curl或pip安裝它:pip install human_curl。

例子:

>>> import human_curl as hurl 
>>> r = hurl.put('http://localhost:8080/openrdf-sesame/repositories/rep/statements', 
... headers = {'Content-Type', 'application/rdf+xml;charset=UTF-8'}, 
... files = (('my_file', open('Tea.rdf')),)) 
>>> r 
    <Response: 201> 

您也可以讀取響應頭,cookie等

+0

human_cur尚未與Python 3兼容。 – ChaimG 2017-07-16 14:53:59