简体   繁体   中英

Alternative to PycURL?

Here's a bit of code that is uploading a file:

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

Now, I'm not liking this PycURL experience at all. Can you suggest any alternative? Maybe urllib2 or httplib can do the same? Can you write some code showing it?

Huge thanks!

Yes, pycurl have a bad API design, cURL is powerful. It have more futures, then urllib/urllib2.

Maybe you want to try to use human_curl. It's python curl wrapper. You can install it from sources https://github.com/lispython/human_curl or by pip: pip install human_curl.

Example:

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

Also you can read response headers, cookies, etc

Using 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

your example converted to 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM