fixed error handling for python 2.7+

This commit is contained in:
Rob Weber 2019-08-19 15:23:48 -05:00
parent d0b1d6bb34
commit 4513eb67f9
6 changed files with 18 additions and 36 deletions

View File

@ -58,7 +58,7 @@ class DropboxAuthorizer:
try: try:
user_token = flow.finish(code) user_token = flow.finish(code)
self._setToken(user_token.access_token) self._setToken(user_token.access_token)
except Exception,e: except Exception as e:
utils.log("Error: %s" % (e,)) utils.log("Error: %s" % (e,))
result = False result = False

View File

@ -1,4 +1,3 @@
import xbmc
import utils as utils import utils as utils
class ZipExtractor: class ZipExtractor:
@ -24,8 +23,7 @@ class ZipExtractor:
#extract the file #extract the file
zipFile.extract(aFile,outLoc) zipFile.extract(aFile,outLoc)
except Exception,e: except Exception as e:
print str(e)
utils.log("Error extracting file") utils.log("Error extracting file")
result = False result = False

View File

@ -156,7 +156,7 @@ class GoogleAuth(ApiAttributeMixin, object):
port_number = port port_number = port
try: try:
httpd = ClientRedirectServer((host_name, port), ClientRedirectHandler) httpd = ClientRedirectServer((host_name, port), ClientRedirectHandler)
except socket.error, e: except socket.error as e:
pass pass
else: else:
success = True success = True
@ -164,26 +164,16 @@ class GoogleAuth(ApiAttributeMixin, object):
if success: if success:
oauth_callback = 'http://%s:%s/' % (host_name, port_number) oauth_callback = 'http://%s:%s/' % (host_name, port_number)
else: else:
print 'Failed to start a local webserver. Please check your firewall'
print 'settings and locally running programs that may be blocking or'
print 'using configured ports. Default ports are 8080 and 8090.'
raise AuthenticationError() raise AuthenticationError()
self.flow.redirect_uri = oauth_callback self.flow.redirect_uri = oauth_callback
authorize_url = self.GetAuthUrl() authorize_url = self.GetAuthUrl()
webbrowser.open(authorize_url, new=1, autoraise=True) webbrowser.open(authorize_url, new=1, autoraise=True)
print 'Your browser has been opened to visit:'
print
print ' ' + authorize_url
print
httpd.handle_request() httpd.handle_request()
if 'error' in httpd.query_params: if 'error' in httpd.query_params:
print 'Authentication request was rejected'
raise AuthenticationRejected('User rejected authentication') raise AuthenticationRejected('User rejected authentication')
if 'code' in httpd.query_params: if 'code' in httpd.query_params:
return httpd.query_params['code'] return httpd.query_params['code']
else: else:
print 'Failed to find "code" in the query parameters of the redirect.'
print 'Try command-line authentication'
raise AuthenticationError('No code found in redirect') raise AuthenticationError('No code found in redirect')
@CheckAuth @CheckAuth
@ -195,10 +185,6 @@ class GoogleAuth(ApiAttributeMixin, object):
""" """
self.flow.redirect_uri = OOB_CALLBACK_URN self.flow.redirect_uri = OOB_CALLBACK_URN
authorize_url = self.GetAuthUrl() authorize_url = self.GetAuthUrl()
print 'Go to the following link in your browser:'
print
print ' ' + authorize_url
print
return raw_input('Enter verification code: ').strip() return raw_input('Enter verification code: ').strip()
def LoadCredentials(self, backend=None): def LoadCredentials(self, backend=None):
@ -309,7 +295,7 @@ class GoogleAuth(ApiAttributeMixin, object):
client_config_file = self.settings['client_config_file'] client_config_file = self.settings['client_config_file']
try: try:
client_type, client_info = clientsecrets.loadfile(client_config_file) client_type, client_info = clientsecrets.loadfile(client_config_file)
except clientsecrets.InvalidClientSecretsError, error: except clientsecrets.InvalidClientSecretsError as error:
raise InvalidConfigError('Invalid client secrets file %s' % error) raise InvalidConfigError('Invalid client secrets file %s' % error)
if not client_type in (clientsecrets.TYPE_WEB, if not client_type in (clientsecrets.TYPE_WEB,
clientsecrets.TYPE_INSTALLED): clientsecrets.TYPE_INSTALLED):
@ -334,7 +320,6 @@ class GoogleAuth(ApiAttributeMixin, object):
self.client_config[config] = self.settings['client_config'][config] self.client_config[config] = self.settings['client_config'][config]
except KeyError: except KeyError:
print config
raise InvalidConfigError('Insufficient client config in settings') raise InvalidConfigError('Insufficient client config in settings')
def GetFlow(self): def GetFlow(self):
@ -374,7 +359,7 @@ class GoogleAuth(ApiAttributeMixin, object):
self.http = httplib2.Http() self.http = httplib2.Http()
try: try:
self.credentials.refresh(self.http) self.credentials.refresh(self.http)
except AccessTokenRefreshError, error: except AccessTokenRefreshError as error:
raise RefreshError('Access token refresh failed: %s' % error) raise RefreshError('Access token refresh failed: %s' % error)
def GetAuthUrl(self, keys = None): def GetAuthUrl(self, keys = None):
@ -414,9 +399,8 @@ class GoogleAuth(ApiAttributeMixin, object):
self.GetFlow() self.GetFlow()
try: try:
self.credentials = self.flow.step2_exchange(code) self.credentials = self.flow.step2_exchange(code)
except FlowExchangeError, e: except FlowExchangeError as e:
raise AuthenticationError('OAuth2 code exchange failed: %s' % e) raise AuthenticationError('OAuth2 code exchange failed: %s' % e)
print 'Authentication successful.'
def Authorize(self): def Authorize(self):
"""Authorizes and builds service. """Authorizes and builds service.

View File

@ -108,7 +108,7 @@ class GoogleDriveFile(ApiAttributeMixin, ApiResource):
""" """
try: try:
return dict.__getitem__(self, key) return dict.__getitem__(self, key)
except KeyError, e: except KeyError as e:
if self.uploaded: if self.uploaded:
raise KeyError(e) raise KeyError(e)
if self.get('id'): if self.get('id'):
@ -180,7 +180,7 @@ class GoogleDriveFile(ApiAttributeMixin, ApiResource):
if file_id: if file_id:
try: try:
metadata = self.auth.service.files().get(fileId=file_id).execute() metadata = self.auth.service.files().get(fileId=file_id).execute()
except errors.HttpError, error: except errors.HttpError as error:
raise ApiRequestError(error) raise ApiRequestError(error)
else: else:
self.uploaded = True self.uploaded = True
@ -244,7 +244,7 @@ class GoogleDriveFile(ApiAttributeMixin, ApiResource):
if self.dirty['content']: if self.dirty['content']:
param['media_body'] = self._BuildMediaBody() param['media_body'] = self._BuildMediaBody()
metadata = self.auth.service.files().insert(**param).execute() metadata = self.auth.service.files().insert(**param).execute()
except errors.HttpError, error: except errors.HttpError as error:
raise ApiRequestError(error) raise ApiRequestError(error)
else: else:
self.uploaded = True self.uploaded = True
@ -268,7 +268,7 @@ class GoogleDriveFile(ApiAttributeMixin, ApiResource):
if self.dirty['content']: if self.dirty['content']:
param['media_body'] = self._BuildMediaBody() param['media_body'] = self._BuildMediaBody()
metadata = self.auth.service.files().update(**param).execute() metadata = self.auth.service.files().update(**param).execute()
except errors.HttpError, error: except errors.HttpError as error:
raise ApiRequestError(error) raise ApiRequestError(error)
else: else:
self.uploaded = True self.uploaded = True
@ -290,7 +290,7 @@ class GoogleDriveFile(ApiAttributeMixin, ApiResource):
param['fileId'] = self.metadata.get('id') param['fileId'] = self.metadata.get('id')
try: try:
metadata = self.auth.service.files().patch(**param).execute() metadata = self.auth.service.files().patch(**param).execute()
except errors.HttpError, error: except errors.HttpError as error:
raise ApiRequestError(error) raise ApiRequestError(error)
else: else:
self.UpdateMetadata(metadata) self.UpdateMetadata(metadata)

View File

@ -120,7 +120,7 @@ def LoadSettingsFile(filename=SETTINGS_FILE):
try: try:
stream = file(filename, 'r') stream = file(filename, 'r')
data = load(stream, Loader=Loader) data = load(stream, Loader=Loader)
except (YAMLError, IOError), e: except (YAMLError, IOError) as e:
print e print e
raise SettingsError(e) raise SettingsError(e)
return data return data

View File

@ -115,7 +115,7 @@ Here is the behavior of operations with relativedelta:
if dt1 and dt2: if dt1 and dt2:
if not isinstance(dt1, datetime.date) or \ if not isinstance(dt1, datetime.date) or \
not isinstance(dt2, datetime.date): not isinstance(dt2, datetime.date):
raise TypeError, "relativedelta only diffs datetime/date" raise TypeError("relativedelta only diffs datetime/date")
if type(dt1) is not type(dt2): if type(dt1) is not type(dt2):
if not isinstance(dt1, datetime.datetime): if not isinstance(dt1, datetime.datetime):
dt1 = datetime.datetime.fromordinal(dt1.toordinal()) dt1 = datetime.datetime.fromordinal(dt1.toordinal())
@ -195,7 +195,7 @@ Here is the behavior of operations with relativedelta:
self.day = yday-ydayidx[idx-1] self.day = yday-ydayidx[idx-1]
break break
else: else:
raise ValueError, "invalid year day (%d)" % yday raise ValueError("invalid year day (%d)" % yday)
self._fix() self._fix()
@ -244,7 +244,7 @@ Here is the behavior of operations with relativedelta:
def __radd__(self, other): def __radd__(self, other):
if not isinstance(other, datetime.date): if not isinstance(other, datetime.date):
raise TypeError, "unsupported type for add operation" raise TypeError("unsupported type for add operation")
elif self._has_time and not isinstance(other, datetime.datetime): elif self._has_time and not isinstance(other, datetime.datetime):
other = datetime.datetime.fromordinal(other.toordinal()) other = datetime.datetime.fromordinal(other.toordinal())
year = (self.year or other.year)+self.years year = (self.year or other.year)+self.years
@ -290,7 +290,7 @@ Here is the behavior of operations with relativedelta:
def __add__(self, other): def __add__(self, other):
if not isinstance(other, relativedelta): if not isinstance(other, relativedelta):
raise TypeError, "unsupported type for add operation" raise TypeError("unsupported type for add operation")
return relativedelta(years=other.years+self.years, return relativedelta(years=other.years+self.years,
months=other.months+self.months, months=other.months+self.months,
days=other.days+self.days, days=other.days+self.days,
@ -310,7 +310,7 @@ Here is the behavior of operations with relativedelta:
def __sub__(self, other): def __sub__(self, other):
if not isinstance(other, relativedelta): if not isinstance(other, relativedelta):
raise TypeError, "unsupported type for sub operation" raise TypeError("unsupported type for sub operation")
return relativedelta(years=other.years-self.years, return relativedelta(years=other.years-self.years,
months=other.months-self.months, months=other.months-self.months,
days=other.days-self.days, days=other.days-self.days,
@ -426,5 +426,5 @@ Here is the behavior of operations with relativedelta:
"hour", "minute", "second", "microsecond"]: "hour", "minute", "second", "microsecond"]:
value = getattr(self, attr) value = getattr(self, attr)
if value is not None: if value is not None:
l.append("%s=%s" % (attr, `value`)) l.append("%s=%s" % (attr, value))
return "%s(%s)" % (self.__class__.__name__, ", ".join(l)) return "%s(%s)" % (self.__class__.__name__, ", ".join(l))