1919 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
2020"""
2121
22- try :
23- import http .client as httplib
24- except ImportError :
25- import httplib
2622import base64
2723import json
2824import decimal
25+ from collections import defaultdict , deque
2926try :
27+ # Python 3
28+ import http .client as httplib
29+ from urllib .request import urlopen , Request
30+ from urllib .error import HTTPError , URLError
3031 import urllib .parse as urlparse
3132except ImportError :
33+ import httplib
34+ from urllib2 import urlopen , Request , HTTPError , URLError
3235 import urlparse
33- from collections import defaultdict , deque
36+
3437from bitcoinrpc .exceptions import TransportException
3538
3639USER_AGENT = "AuthServiceProxy/0.1"
@@ -56,32 +59,36 @@ def __init__(self, service_url):
5659 self .parsed_url .password )
5760 authpair = authpair .encode ('utf8' )
5861 self .auth_header = "Basic " .encode ('utf8' ) + base64 .b64encode (authpair )
59- if self .parsed_url .scheme == 'https' :
60- self .connection = httplib .HTTPSConnection (self .parsed_url .hostname ,
61- port , None , None , False ,
62- HTTP_TIMEOUT )
63- else :
64- self .connection = httplib .HTTPConnection (self .parsed_url .hostname ,
65- port , False , HTTP_TIMEOUT )
62+
63+ self .uri = '%s://%s:%d' % (self .parsed_url .scheme ,
64+ self .parsed_url .hostname ,
65+ self .parsed_url .port )
6666
6767 def request (self , serialized_data ):
68- self .connection .request ('POST' , self .parsed_url .path , serialized_data ,
69- {'Host' : self .parsed_url .hostname ,
70- 'User-Agent' : USER_AGENT ,
71- 'Authorization' : self .auth_header ,
72- 'Content-type' : 'application/json' })
68+ resp = None
69+ httpresp = False
70+
71+ request = Request (self .uri )
72+ request .add_header ('Authorization' , self .auth_header )
73+ try :
74+ httpresp = urlopen (request , serialized_data , timeout = HTTP_TIMEOUT )
75+ except HTTPError , err :
76+ resp = err .read ()
77+ except URLError , err :
78+ raise TransportException (err .reason , code = err .errno ,
79+ protocol = self .parsed_url .scheme )
7380
74- httpresp = self .connection .getresponse ()
7581 if httpresp is None :
76- self . _raise_exception ({
77- 'code' : - 342 , 'message' : 'missing HTTP response from server' } )
78- elif httpresp . status == httplib .FORBIDDEN :
82+ raise TransportException ( 'missing HTTP response from the server' ,
83+ code = - 342 , protocol = self . parsed_url . scheme )
84+ elif httpresp and httpresp . code == httplib .FORBIDDEN :
7985 msg = "bitcoind returns 403 Forbidden. Is your IP allowed?"
8086 raise TransportException (msg , code = 403 ,
8187 protocol = self .parsed_url .scheme ,
8288 raw_detail = httpresp )
8389
84- resp = httpresp .read ()
90+ if resp is None :
91+ resp = httpresp .read ()
8592 return resp .decode ('utf8' )
8693
8794
0 commit comments