3

这是上传文件的一些代码:

  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 可以做同样的事情?你能写一些代码来显示它吗?

非常感谢!

4

3 回答 3

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 等

于 2011-09-08T08:27:21.243 回答
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
于 2009-11-05T20:36:16.463 回答
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()
于 2011-06-23T20:46:20.757 回答