<s> import posixpath <EOL> from oslo_log import log as logging <EOL> from oslo_serialization import jsonutils as json <EOL> import six <EOL> from six . moves import urllib <EOL> from sahara . i18n import _LW <EOL> from sahara . plugins . cdh import exceptions as ex <EOL> LOG = logging . getLogger ( __name__ ) <EOL> class HttpClient ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , base_url , exc_class = ex . CMApiException ) : <EOL> """<STR_LIT>""" <EOL> self . _base_url = base_url . rstrip ( '<STR_LIT:/>' ) <EOL> self . _exc_class = exc_class <EOL> self . _headers = { } <EOL> self . _passmgr = urllib . request . HTTPPasswordMgrWithDefaultRealm ( ) <EOL> authhandler = urllib . request . HTTPBasicAuthHandler ( self . _passmgr ) <EOL> cookiejar = six . moves . http_cookiejar . CookieJar ( ) <EOL> self . _opener = urllib . request . build_opener ( <EOL> urllib . request . HTTPErrorProcessor ( ) , <EOL> urllib . request . HTTPCookieProcessor ( cookiejar ) , <EOL> authhandler ) <EOL> def set_basic_auth ( self , username , password , realm ) : <EOL> """<STR_LIT>""" <EOL> self . _passmgr . add_password ( realm , self . _base_url , username , password ) <EOL> return self <EOL> def set_headers ( self , headers ) : <EOL> """<STR_LIT>""" <EOL> self . _headers = headers <EOL> return self <EOL> @ property <EOL> def base_url ( self ) : <EOL> return self . _base_url <EOL> def _get_headers ( self , headers ) : <EOL> res = self . _headers . copy ( ) <EOL> if headers : <EOL> res . update ( headers ) <EOL> return res <EOL> def execute ( self , http_method , path , params = None , data = None , headers = None ) : <EOL> """<STR_LIT>""" <EOL> url = self . _make_url ( path , params ) <EOL> if http_method in ( "<STR_LIT:GET>" , "<STR_LIT>" ) : <EOL> if data is not None : <EOL> LOG . warning ( _LW ( "<STR_LIT>" <EOL> "<STR_LIT>" ) . format ( method = http_method , <EOL> path = path ) ) <EOL> data = None <EOL> request = urllib . request . Request ( url , data ) <EOL> request . get_method = lambda : http_method <EOL> headers = self . _get_headers ( headers ) <EOL> for k , v in headers . items ( ) : <EOL> request . add_header ( k , v ) <EOL> LOG . debug ( "<STR_LIT>" . format ( method = http_method , <EOL> url = url ) ) <EOL> try : <EOL> return self . _opener . open ( request ) <EOL> except urllib . error . HTTPError as ex : <EOL> message = six . text_type ( ex ) <EOL> try : <EOL> json_body = json . loads ( message ) <EOL> message = json_body [ '<STR_LIT:message>' ] <EOL> except ( ValueError , KeyError ) : <EOL> pass <EOL> raise self . _exc_class ( message ) <EOL> def _make_url ( self , path , params ) : <EOL> res = self . _base_url <EOL> if path : <EOL> res += posixpath . normpath ( '<STR_LIT:/>' + path . lstrip ( '<STR_LIT:/>' ) ) <EOL> if params : <EOL> param_str = urllib . parse . urlencode ( params , True ) <EOL> res += '<STR_LIT:?>' + param_str <EOL> return res </s>
