在curl中,我这样做:
curl -u email:password http://api.foursquare.com/v1/venue.json?vid=2393749
我该如何在Python中完成同样的事情?
import pycurl
from StringIO import StringIO
response_buffer = StringIO()
curl = pycurl.Curl()
curl.setopt(curl.URL, "http://api.foursquare.com/v1/venue.json?vid=2393749")
curl.setopt(curl.USERPWD, '%s:%s' % ('youruser', 'yourpassword'))
curl.setopt(curl.WRITEFUNCTION, response_buffer.write)
curl.perform()
curl.close()
response_value = response_buffer.getvalue()
import urllib2
import base64
req = urllib2.Request('http://api.foursquare.com/v1/venue.json?vid=%s' % self.venue_id)
req.add_header('Authorization: Basic ',base64.b64encode('email:password'))
res = urllib2.urlopen(req)
我更喜欢通过子进程运行命令行curl。这样可以避免Python、pycurl和libcurl之间的潜在版本匹配问题。观察到pycurl已经两年没有更新,并且只支持Python 2.5,这让我感到担忧。 -- John
import subprocess
def curl(*args):
curl_path = '/usr/bin/curl'
curl_list = [curl_path]
for arg in args:
curl_list.append(arg)
curl_result = subprocess.Popen(
curl_list,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE).communicate()[0]
return curl_result
answer = curl('-u', 'email:password', 'http://api.foursquare.com/v1/venue.json?vid=2393749')
r = hurl.get('http://api.foursquare.com/v1/venue.json?vid=2393749', auth=('email','password'))
r.content中的Json数据
在SO上有一个关于教程的讨论
一个典型的例子:
import sys
import pycurl
class ContentCallback:
def __init__(self):
self.contents = ''
def content_callback(self, buf):
self.contents = self.contents + buf
t = ContentCallback()
curlObj = pycurl.Curl()
curlObj.setopt(curlObj.URL, 'http://www.google.com')
curlObj.setopt(curlObj.WRITEFUNCTION, t.content_callback)
curlObj.perform()
curlObj.close()
print t.contents
pycurl
,但并非必须。完全可以使用标准库。请参见我上面链接的问题。 - Matthew Flaschen