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也能做到同样的事情?能不能给我写点代码示范一下?
非常感谢!
3 个回答
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的设计不太好,但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>
此外,你还可以读取响应头、cookies等信息。
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