Python code like curl
Here's the equivalent in pycurl:
import pycurlfrom StringIO import StringIOresponse_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()
"The problem could be that the Python libraries, per HTTP-Standard, first send an unauthenticated request, and then only if it's answered with a 401 retry, are the correct credentials sent. If the Foursquare servers don't do "totally standard authentication" then the libraries won't work.
Try using headers to do authentication:"
taked from Python urllib2 Basic Auth Problem
import urllib2import base64req = 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)
I'm more comfortable running the command line curl through subprocess. This avoids all of the potential version matching headaches of python, pycurl, and libcurl. The observation that pycurl hasn't been touched in 2 years, and is only listed as suppported through Python 2.5, made me wary. -- 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')