PycURL的替代品是什么?

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

非常感谢!


问题是我现在正在尝试对这个存储库发出查询,但curl给了我很多麻烦。所以,我想知道是否有另一种方法来解决这个问题。 再次感谢。 - pns
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等内容。

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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接