21
21
import urllib
22
22
import httplib2
23
23
import socket
24
+ import socks
24
25
from urllib2 import URLError
25
26
import urlparse
26
27
import string
@@ -59,17 +60,20 @@ class Api(object):
59
60
}
60
61
61
62
domain = 'bit.ly'
63
+ proxy_info = None
62
64
63
65
def get_api_domain (self ):
64
66
return self .ALLOWED_API_DOMAINS [self .domain ]
65
67
66
68
""" API class for bit.ly """
67
- def __init__ (self , login , apikey , domain = None ):
69
+ def __init__ (self , login , apikey , domain = None , proxy_info = None ):
68
70
self .login = login
69
71
self .apikey = apikey
70
72
self ._urllib = httplib2
71
73
if domain is not None :
72
74
self .domain = domain
75
+ if proxy_info :
76
+ self .proxy_info = proxy_info
73
77
74
78
def shorten (self , longURLs , params = {}):
75
79
"""
@@ -84,6 +88,7 @@ def shorten(self, longURLs, params={}):
84
88
85
89
request = self ._getURL ("shorten" , longURLs , params )
86
90
result = self ._fetchUrl (request )
91
+
87
92
json = simplejson .loads (result )
88
93
Api ._CheckForError (json )
89
94
@@ -176,16 +181,30 @@ def _fetchUrl(self, url):
176
181
# Open and return the URL
177
182
try :
178
183
if self ._urllib is httplib2 :
179
- http = httplib2 .Http (timeout = TIMEOUT )
184
+ params = {
185
+ 'timeout' : TIMEOUT
186
+ }
187
+
188
+ if self .proxy_info is not None :
189
+ try :
190
+ host = self .proxy_info ['HOST' ]
191
+ port = self .proxy_info ['PORT' ]
192
+ except KeyError , err :
193
+ raise ValueError ('You should supply a value for HOST and PORT when working with proxies. %s' % err )
194
+
195
+ params .update (
196
+ {'proxy_info' : httplib2 .ProxyInfo (socks .PROXY_TYPE_HTTP , host , port )}
197
+ )
198
+ http = httplib2 .Http (** params )
180
199
resp , content = http .request (url )
181
200
url_data = content
182
201
else :
183
202
url_data = self ._urllib .urlopen (url = url ).read ()
184
203
185
204
except (URLError , socket .error ), err :
186
- # nasty bit of hack, i know but unfortunatly urllib2 has no smart way of telling me
187
- # that it was an timeout error
188
- if hasattr (err ,'reason' ) and err .reason == 'urlopen error timed out' or unicode (err ) == u'timed out' :
205
+ # nasty bit of hack, i know but unfortunatly neither urllib2 ou httplib2 has a smart way of telling me
206
+ # that it was a timeout error
207
+ if hasattr (err , 'reason' ) and err .reason == 'urlopen error timed out' or unicode (err ) == u'timed out' :
189
208
raise BitlyTimeoutError ('The url %s has timed out' % url )
190
209
raise err
191
210
0 commit comments