以下是上传文件的一些代码:
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 :(得分:4)
是的,pycurl的API设计不好,cURL功能强大。它有更多的期货,然后是urllib / urllib2。
也许你想尝试使用human_curl。这是python 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等
答案 1 :(得分: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
答案 2 :(得分: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()