From 19b82a022cc58e702fe9061c3347cec471dc4da2 Mon Sep 17 00:00:00 2001 From: Stuart McLaren Date: Tue, 26 Mar 2013 12:14:55 +0000 Subject: [PATCH] Standardize on newer except syntax We currently have a mix of 'except X, y:' and 'except X as y:' syntax. Standardize on the newer 'except as' form. This patch was generated automatically using: find * -type f -name 'glance-*' ! -name '*\.conf' ! -name '*\.ini' -o \ -name '*\.py' | xargs 2to3 -f except | patch -p0 Addresses bug 1160331. Change-Id: Ica8d1303973af64d0406457267ee75f608e869d0 --- bin/glance-api | 4 +-- bin/glance-cache-cleaner | 2 +- bin/glance-cache-manage | 4 +-- bin/glance-cache-prefetcher | 2 +- bin/glance-cache-pruner | 2 +- bin/glance-control | 2 +- bin/glance-manage | 4 +-- bin/glance-registry | 2 +- bin/glance-scrubber | 2 +- glance/api/common.py | 4 +-- glance/api/v1/images.py | 36 ++++++++++----------- glance/api/v1/members.py | 20 ++++++------ glance/api/v2/image_data.py | 16 ++++----- glance/common/client.py | 2 +- glance/common/config.py | 2 +- glance/common/utils.py | 6 ++-- glance/common/wsgi.py | 6 ++-- glance/db/sqlalchemy/api.py | 8 ++--- glance/db/sqlalchemy/migration.py | 6 ++-- glance/image_cache/__init__.py | 4 +-- glance/image_cache/drivers/sqlite.py | 6 ++-- glance/image_cache/drivers/xattr.py | 2 +- glance/notifier/__init__.py | 6 ++-- glance/notifier/notify_kombu.py | 8 ++--- glance/registry/api/v1/images.py | 6 ++-- glance/registry/api/v1/members.py | 8 ++--- glance/store/rbd.py | 2 +- glance/store/s3.py | 4 +-- glance/store/swift.py | 14 ++++---- glance/tests/functional/__init__.py | 2 +- glance/tests/functional/store/test_swift.py | 6 ++-- glance/tests/functional/store_utils.py | 22 ++++++------- glance/tests/functional/v1/test_rbd.py | 6 ++-- glance/tests/unit/test_migrations.py | 2 +- glance/tests/unit/test_swift_store.py | 2 +- glance/tests/utils.py | 2 +- 36 files changed, 116 insertions(+), 116 deletions(-) diff --git a/bin/glance-api b/bin/glance-api index cd493d68cd..83cdc59ab0 100755 --- a/bin/glance-api +++ b/bin/glance-api @@ -59,7 +59,7 @@ if __name__ == '__main__': server = wsgi.Server() server.start(config.load_paste_app(), default_port=9292) server.wait() - except exception.WorkerCreationFailure, e: + except exception.WorkerCreationFailure as e: fail(2, e) - except RuntimeError, e: + except RuntimeError as e: fail(1, e) diff --git a/bin/glance-cache-cleaner b/bin/glance-cache-cleaner index 00589bbd2f..c26814c517 100755 --- a/bin/glance-cache-cleaner +++ b/bin/glance-cache-cleaner @@ -62,5 +62,5 @@ if __name__ == '__main__': app = cleaner.Cleaner() app.run() - except RuntimeError, e: + except RuntimeError as e: sys.exit("ERROR: %s" % e) diff --git a/bin/glance-cache-manage b/bin/glance-cache-manage index cf504c583c..9fdcb11c56 100755 --- a/bin/glance-cache-manage +++ b/bin/glance-cache-manage @@ -64,7 +64,7 @@ def catch_error(action): except exception.Forbidden: print "Not authorized to make this request." return FAILURE - except Exception, e: + except Exception as e: options = args[0] if options.debug: raise @@ -512,5 +512,5 @@ Commands: if options.verbose: print "Completed in %-0.4f sec." % (end_time - start_time) sys.exit(result) - except (RuntimeError, NotImplementedError), e: + except (RuntimeError, NotImplementedError) as e: print "ERROR: ", e diff --git a/bin/glance-cache-prefetcher b/bin/glance-cache-prefetcher index fa1a373b23..914f62365d 100755 --- a/bin/glance-cache-prefetcher +++ b/bin/glance-cache-prefetcher @@ -57,5 +57,5 @@ if __name__ == '__main__': app = prefetcher.Prefetcher() app.run() - except RuntimeError, e: + except RuntimeError as e: sys.exit("ERROR: %s" % e) diff --git a/bin/glance-cache-pruner b/bin/glance-cache-pruner index 85a4ff910c..9f6d3b4112 100755 --- a/bin/glance-cache-pruner +++ b/bin/glance-cache-pruner @@ -54,5 +54,5 @@ if __name__ == '__main__': app = pruner.Pruner() app.run() - except RuntimeError, e: + except RuntimeError as e: sys.exit("ERROR: %s" % e) diff --git a/bin/glance-control b/bin/glance-control index fc8a27268d..ebd2eb2228 100755 --- a/bin/glance-control +++ b/bin/glance-control @@ -172,7 +172,7 @@ def do_start(verb, pid_file, server, args): redirect_stdio(server, capture_output) try: os.execlp('%s' % server, *args) - except OSError, e: + except OSError as e: msg = 'unable to launch %s. Got error: %s' % (server, e) sys.exit(msg) sys.exit(0) diff --git a/bin/glance-manage b/bin/glance-manage index 1a3819ef36..ef840921e2 100755 --- a/bin/glance-manage +++ b/bin/glance-manage @@ -121,12 +121,12 @@ def main(): config.parse_args(default_config_files=default_cfg_files, usage="%(prog)s [options] ") log.setup('glance') - except RuntimeError, e: + except RuntimeError as e: sys.exit("ERROR: %s" % e) try: CONF.command.func() - except exception.GlanceException, e: + except exception.GlanceException as e: sys.exit("ERROR: %s" % e) diff --git a/bin/glance-registry b/bin/glance-registry index cdaf7e25d7..1f197665ba 100755 --- a/bin/glance-registry +++ b/bin/glance-registry @@ -49,5 +49,5 @@ if __name__ == '__main__': server = wsgi.Server() server.start(config.load_paste_app(), default_port=9191) server.wait() - except RuntimeError, e: + except RuntimeError as e: sys.exit("ERROR: %s" % e) diff --git a/bin/glance-scrubber b/bin/glance-scrubber index c1c236521d..189a6a4171 100755 --- a/bin/glance-scrubber +++ b/bin/glance-scrubber @@ -74,5 +74,5 @@ if __name__ == '__main__': import eventlet pool = eventlet.greenpool.GreenPool(1000) scrubber = app.run(pool) - except RuntimeError, e: + except RuntimeError as e: sys.exit("ERROR: %s" % e) diff --git a/glance/api/common.py b/glance/api/common.py index ee7c8322ee..9b3b6ded25 100644 --- a/glance/api/common.py +++ b/glance/api/common.py @@ -37,7 +37,7 @@ def size_checked_iter(response, image_meta, expected_size, image_iter, for chunk in image_iter: yield chunk bytes_written += len(chunk) - except Exception, err: + except Exception as err: msg = _("An error occurred reading from backend storage " "for image %(image_id)s: %(err)s") % locals() LOG.error(msg) @@ -72,7 +72,7 @@ def image_send_notification(bytes_written, expected_size, image_meta, request, notify('image.send', payload) - except Exception, err: + except Exception as err: msg = _("An error occurred during image.send" " notification: %(err)s") % locals() LOG.error(msg) diff --git a/glance/api/v1/images.py b/glance/api/v1/images.py index 4993a28491..8ee40f0783 100644 --- a/glance/api/v1/images.py +++ b/glance/api/v1/images.py @@ -169,7 +169,7 @@ class Controller(controller.BaseController): params = self._get_query_params(req) try: images = registry.get_images_list(req.context, **params) - except exception.Invalid, e: + except exception.Invalid as e: raise HTTPBadRequest(explanation="%s" % e) return dict(images=images) @@ -209,7 +209,7 @@ class Controller(controller.BaseController): # information to the API end user... for image in images: del image['location'] - except exception.Invalid, e: + except exception.Invalid as e: raise HTTPBadRequest(explanation="%s" % e) return dict(images=images) @@ -297,7 +297,7 @@ class Controller(controller.BaseController): def _get_from_store(context, where): try: image_data, image_size = get_from_backend(context, where) - except exception.NotFound, e: + except exception.NotFound as e: raise HTTPNotFound(explanation="%s" % e) image_size = int(image_size) if image_size else None return image_data, image_size @@ -374,7 +374,7 @@ class Controller(controller.BaseController): raise HTTPConflict(explanation=msg, request=req, content_type="text/plain") - except exception.Invalid, e: + except exception.Invalid as e: msg = (_("Failed to reserve image. Got error: %(e)s") % locals()) for line in msg.split('\n'): LOG.debug(line) @@ -476,13 +476,13 @@ class Controller(controller.BaseController): return location - except exception.Duplicate, e: + except exception.Duplicate as e: msg = _("Attempt to upload duplicate image: %s") % e LOG.debug(msg) self._safe_kill(req, image_id) raise HTTPConflict(explanation=msg, request=req) - except exception.Forbidden, e: + except exception.Forbidden as e: msg = _("Forbidden upload attempt: %s") % e LOG.debug(msg) self._safe_kill(req, image_id) @@ -490,7 +490,7 @@ class Controller(controller.BaseController): request=req, content_type="text/plain") - except exception.StorageFull, e: + except exception.StorageFull as e: msg = _("Image storage media is full: %s") % e LOG.error(msg) self._safe_kill(req, image_id) @@ -498,7 +498,7 @@ class Controller(controller.BaseController): raise HTTPRequestEntityTooLarge(explanation=msg, request=req, content_type='text/plain') - except exception.StorageWriteDenied, e: + except exception.StorageWriteDenied as e: msg = _("Insufficient permissions on image storage media: %s") % e LOG.error(msg) self._safe_kill(req, image_id) @@ -506,7 +506,7 @@ class Controller(controller.BaseController): raise HTTPServiceUnavailable(explanation=msg, request=req, content_type='text/plain') - except exception.ImageSizeLimitExceeded, e: + except exception.ImageSizeLimitExceeded as e: msg = _("Denying attempt to upload image larger than %d bytes." % CONF.image_size_cap) LOG.info(msg) @@ -514,7 +514,7 @@ class Controller(controller.BaseController): raise HTTPBadRequest(explanation=msg, request=req, content_type='text/plain') - except HTTPError, e: + except HTTPError as e: self._safe_kill(req, image_id) #NOTE(bcwaldon): Ideally, we would just call 'raise' here, # but something in the above function calls is affecting the @@ -522,7 +522,7 @@ class Controller(controller.BaseController): # caught exception. raise e - except Exception, e: + except Exception as e: LOG.exception(_("Failed to upload image")) self._safe_kill(req, image_id) raise HTTPInternalServerError(request=req) @@ -547,7 +547,7 @@ class Controller(controller.BaseController): self.notifier.info("image.activate", redact_loc(image_meta_data)) self.notifier.info("image.update", redact_loc(image_meta_data)) return image_meta_data - except exception.Invalid, e: + except exception.Invalid as e: msg = (_("Failed to activate image. Got error: %(e)s") % locals()) LOG.debug(msg) @@ -577,7 +577,7 @@ class Controller(controller.BaseController): """ try: self._kill(req, image_id) - except Exception, e: + except Exception as e: LOG.error(_("Unable to kill image %(id)s: " "%(exc)s") % ({'id': image_id, 'exc': repr(e)})) @@ -775,21 +775,21 @@ class Controller(controller.BaseController): image_meta = self._handle_source(req, id, image_meta, image_data) - except exception.Invalid, e: + except exception.Invalid as e: msg = (_("Failed to update image metadata. Got error: %(e)s") % locals()) LOG.debug(msg) raise HTTPBadRequest(explanation=msg, request=req, content_type="text/plain") - except exception.NotFound, e: + except exception.NotFound as e: msg = (_("Failed to find image to update: %(e)s") % locals()) for line in msg.split('\n'): LOG.info(line) raise HTTPNotFound(explanation=msg, request=req, content_type="text/plain") - except exception.Forbidden, e: + except exception.Forbidden as e: msg = (_("Forbidden to update image: %(e)s") % locals()) for line in msg.split('\n'): LOG.info(line) @@ -859,14 +859,14 @@ class Controller(controller.BaseController): # See https://bugs.launchpad.net/glance/+bug/747799 if image['location']: self._initiate_deletion(req, image['location'], id) - except exception.NotFound, e: + except exception.NotFound as e: msg = (_("Failed to find image to delete: %(e)s") % locals()) for line in msg.split('\n'): LOG.info(line) raise HTTPNotFound(explanation=msg, request=req, content_type="text/plain") - except exception.Forbidden, e: + except exception.Forbidden as e: msg = (_("Forbidden to delete image: %(e)s") % locals()) for line in msg.split('\n'): LOG.info(line) diff --git a/glance/api/v1/members.py b/glance/api/v1/members.py index f7d30b2710..c6a9cbfa2b 100644 --- a/glance/api/v1/members.py +++ b/glance/api/v1/members.py @@ -69,11 +69,11 @@ class Controller(controller.BaseController): try: registry.delete_member(req.context, image_id, id) self._update_store_acls(req, image_id) - except exception.NotFound, e: + except exception.NotFound as e: msg = "%s" % e LOG.debug(msg) raise webob.exc.HTTPNotFound(msg) - except exception.Forbidden, e: + except exception.Forbidden as e: msg = "%s" % e LOG.debug(msg) raise webob.exc.HTTPNotFound(msg) @@ -107,15 +107,15 @@ class Controller(controller.BaseController): try: registry.add_member(req.context, image_id, id, can_share) self._update_store_acls(req, image_id) - except exception.Invalid, e: + except exception.Invalid as e: msg = "%s" % e LOG.debug(msg) raise webob.exc.HTTPBadRequest(explanation=msg) - except exception.NotFound, e: + except exception.NotFound as e: msg = "%s" % e LOG.debug(msg) raise webob.exc.HTTPNotFound(msg) - except exception.Forbidden, e: + except exception.Forbidden as e: msg = "%s" % e LOG.debug(msg) raise webob.exc.HTTPNotFound(msg) @@ -138,15 +138,15 @@ class Controller(controller.BaseController): try: registry.replace_members(req.context, image_id, body) self._update_store_acls(req, image_id) - except exception.Invalid, e: + except exception.Invalid as e: msg = "%s" % e LOG.debug(msg) raise webob.exc.HTTPBadRequest(explanation=msg) - except exception.NotFound, e: + except exception.NotFound as e: msg = "%s" % e LOG.debug(msg) raise webob.exc.HTTPNotFound(msg) - except exception.Forbidden, e: + except exception.Forbidden as e: msg = "%s" % e LOG.debug(msg) raise webob.exc.HTTPNotFound(msg) @@ -168,11 +168,11 @@ class Controller(controller.BaseController): """ try: members = registry.get_member_images(req.context, id) - except exception.NotFound, e: + except exception.NotFound as e: msg = "%s" % e LOG.debug(msg) raise webob.exc.HTTPNotFound(msg) - except exception.Forbidden, e: + except exception.Forbidden as e: msg = "%s" % e LOG.debug(msg) raise webob.exc.HTTPForbidden(msg) diff --git a/glance/api/v2/image_data.py b/glance/api/v2/image_data.py index 4f7961bcb4..9d69053085 100644 --- a/glance/api/v2/image_data.py +++ b/glance/api/v2/image_data.py @@ -52,39 +52,39 @@ class ImageDataController(object): image_repo.save(image) image.set_data(data, size) image_repo.save(image) - except ValueError, e: + except ValueError as e: LOG.debug("Cannot save data for image %s: %s", image_id, e) raise webob.exc.HTTPBadRequest(explanation=unicode(e)) - except exception.Duplicate, e: + except exception.Duplicate as e: msg = _("Unable to upload duplicate image data for image: %s") LOG.debug(msg % image_id) raise webob.exc.HTTPConflict(explanation=msg, request=req) - except exception.Forbidden, e: + except exception.Forbidden as e: msg = _("Not allowed to upload image data for image %s") LOG.debug(msg % image_id) raise webob.exc.HTTPForbidden(explanation=msg, request=req) - except exception.NotFound, e: + except exception.NotFound as e: raise webob.exc.HTTPNotFound(explanation=unicode(e)) - except exception.StorageFull, e: + except exception.StorageFull as e: msg = _("Image storage media is full: %s") % e LOG.error(msg) raise webob.exc.HTTPRequestEntityTooLarge(explanation=msg, request=req) - except exception.StorageWriteDenied, e: + except exception.StorageWriteDenied as e: msg = _("Insufficient permissions on image storage media: %s") % e LOG.error(msg) raise webob.exc.HTTPServiceUnavailable(explanation=msg, request=req) - except webob.exc.HTTPError, e: + except webob.exc.HTTPError as e: LOG.error(_("Failed to upload image data due to HTTP error")) raise - except Exception, e: + except Exception as e: LOG.exception(_("Failed to upload image data due to " "internal error")) raise diff --git a/glance/common/client.py b/glance/common/client.py index 75bf147adc..e2663140d6 100644 --- a/glance/common/client.py +++ b/glance/common/client.py @@ -518,7 +518,7 @@ class BaseClient(object): raise exception.UnexpectedStatus(status=status_code, body=res.read()) - except (socket.error, IOError), e: + except (socket.error, IOError) as e: raise exception.ClientConnectionError(e) def _seekable(self, body): diff --git a/glance/common/config.py b/glance/common/config.py index 38aca69ca5..2a92584209 100644 --- a/glance/common/config.py +++ b/glance/common/config.py @@ -210,7 +210,7 @@ def load_paste_app(app_name=None): CONF.log_opt_values(logger, logging.DEBUG) return app - except (LookupError, ImportError), e: + except (LookupError, ImportError) as e: msg = _("Unable to load %(app_name)s from " "configuration file %(conf_file)s." "\nGot: %(e)r") % locals() diff --git a/glance/common/utils.py b/glance/common/utils.py index 82fedb0001..a85bb3cbdf 100644 --- a/glance/common/utils.py +++ b/glance/common/utils.py @@ -83,7 +83,7 @@ def cooperative_iter(iter): for chunk in iter: sleep(0) yield chunk - except Exception, err: + except Exception as err: msg = _("Error: cooperative_iter exception %s") % err LOG.error(msg) raise @@ -259,7 +259,7 @@ def bool_from_string(subject): def safe_mkdirs(path): try: os.makedirs(path) - except OSError, e: + except OSError as e: if e.errno != errno.EEXIST: raise @@ -267,7 +267,7 @@ def safe_mkdirs(path): def safe_remove(path): try: os.remove(path) - except OSError, e: + except OSError as e: if e.errno != errno.ENOENT: raise diff --git a/glance/common/wsgi.py b/glance/common/wsgi.py index 6a8a245714..01ea48cbbb 100644 --- a/glance/common/wsgi.py +++ b/glance/common/wsgi.py @@ -138,7 +138,7 @@ def get_socket(default_port): if use_ssl: sock = wrap_ssl(sock) - except socket.error, err: + except socket.error as err: if err.args[0] != errno.EADDRINUSE: raise eventlet.sleep(0.1) @@ -225,7 +225,7 @@ class Server(object): self.running = False else: self.run_child() - except OSError, err: + except OSError as err: if err.errno not in (errno.EINTR, errno.ECHILD): raise except KeyboardInterrupt: @@ -281,7 +281,7 @@ class Server(object): self.application, log=WritableLogger(self.logger), custom_pool=self.pool) - except socket.error, err: + except socket.error as err: if err[0] != errno.EINVAL: raise self.pool.waitall() diff --git a/glance/db/sqlalchemy/api.py b/glance/db/sqlalchemy/api.py index 425823a600..9214063816 100644 --- a/glance/db/sqlalchemy/api.py +++ b/glance/db/sqlalchemy/api.py @@ -73,7 +73,7 @@ def ping_listener(dbapi_conn, connection_rec, connection_proxy): try: dbapi_conn.cursor().execute('select 1') - except dbapi_conn.OperationalError, ex: + except dbapi_conn.OperationalError as ex: if ex.args[0] in (2006, 2013, 2014, 2045, 2055): msg = 'Got mysql server has gone away: %s' % ex LOG.warn(msg) @@ -154,7 +154,7 @@ def get_engine(): _ENGINE.connect = wrap_db_error(_ENGINE.connect) _ENGINE.connect() - except Exception, err: + except Exception as err: msg = _("Error configuring registry database with supplied " "sql_connection. Got error: %s") % err LOG.error(msg) @@ -206,7 +206,7 @@ def wrap_db_error(f): def _wrap(*args, **kwargs): try: return f(*args, **kwargs) - except sqlalchemy.exc.OperationalError, e: + except sqlalchemy.exc.OperationalError as e: if not is_db_connection_error(e.args[0]): raise @@ -218,7 +218,7 @@ def wrap_db_error(f): time.sleep(_RETRY_INTERVAL) try: return f(*args, **kwargs) - except sqlalchemy.exc.OperationalError, e: + except sqlalchemy.exc.OperationalError as e: if (remaining_attempts == 0 or not is_db_connection_error(e.args[0])): raise diff --git a/glance/db/sqlalchemy/migration.py b/glance/db/sqlalchemy/migration.py index d17b70dfa8..f94865b829 100644 --- a/glance/db/sqlalchemy/migration.py +++ b/glance/db/sqlalchemy/migration.py @@ -45,7 +45,7 @@ def db_version(): sql_connection = CONF.sql_connection try: return versioning_api.db_version(sql_connection, repo_path) - except versioning_exceptions.DatabaseNotControlledError, e: + except versioning_exceptions.DatabaseNotControlledError as e: msg = (_("database is not under migration control")) raise exception.DatabaseMigrationError(msg) @@ -88,7 +88,7 @@ def version_control(version=None): sql_connection = CONF.sql_connection try: _version_control(version) - except versioning_exceptions.DatabaseAlreadyControlledError, e: + except versioning_exceptions.DatabaseAlreadyControlledError as e: msg = (_("database is already under migration control")) raise exception.DatabaseMigrationError(msg) @@ -116,7 +116,7 @@ def db_sync(version=None, current_version=None): sql_connection = CONF.sql_connection try: _version_control(current_version or 0) - except versioning_exceptions.DatabaseAlreadyControlledError, e: + except versioning_exceptions.DatabaseAlreadyControlledError as e: pass if current_version is None: diff --git a/glance/image_cache/__init__.py b/glance/image_cache/__init__.py index 82af9f510b..aa0d0d44bf 100644 --- a/glance/image_cache/__init__.py +++ b/glance/image_cache/__init__.py @@ -60,7 +60,7 @@ class ImageCache(object): self.driver_class = importutils.import_class(driver_module) LOG.info(_("Image cache loaded driver '%s'.") % driver_name) - except ImportError, import_err: + except ImportError as import_err: LOG.warn(_("Image cache driver " "'%(driver_name)s' failed to load. " "Got error: '%(import_err)s.") % locals()) @@ -78,7 +78,7 @@ class ImageCache(object): try: self.driver = self.driver_class() self.driver.configure() - except exception.BadDriverConfiguration, config_err: + except exception.BadDriverConfiguration as config_err: driver_module = self.driver_class.__module__ LOG.warn(_("Image cache driver " "'%(driver_module)s' failed to configure. " diff --git a/glance/image_cache/drivers/sqlite.py b/glance/image_cache/drivers/sqlite.py index 3d803773c3..ccae33cdce 100644 --- a/glance/image_cache/drivers/sqlite.py +++ b/glance/image_cache/drivers/sqlite.py @@ -62,7 +62,7 @@ class SqliteConnection(sqlite3.Connection): while True: try: return call() - except sqlite3.OperationalError, e: + except sqlite3.OperationalError as e: if 'locked' not in str(e): raise sleep(0.05) @@ -116,7 +116,7 @@ class Driver(base.Driver): ); """) conn.close() - except sqlite3.DatabaseError, e: + except sqlite3.DatabaseError as e: msg = _("Failed to initialize the image cache database. " "Got error: %s") % e LOG.error(msg) @@ -380,7 +380,7 @@ class Driver(base.Driver): conn.execute('PRAGMA temp_store = MEMORY') try: yield conn - except sqlite3.DatabaseError, e: + except sqlite3.DatabaseError as e: msg = _("Error executing SQLite call. Got error: %s") % e LOG.error(msg) conn.rollback() diff --git a/glance/image_cache/drivers/xattr.py b/glance/image_cache/drivers/xattr.py index ddaff94632..07982353b1 100644 --- a/glance/image_cache/drivers/xattr.py +++ b/glance/image_cache/drivers/xattr.py @@ -101,7 +101,7 @@ class Driver(base.Driver): fake_file.flush() try: set_xattr(fake_image_filepath, 'hits', '1') - except IOError, e: + except IOError as e: if e.errno == errno.EOPNOTSUPP: msg = _("The device housing the image cache directory " "%(image_cache_dir)s does not support xattr. It is " diff --git a/glance/notifier/__init__.py b/glance/notifier/__init__.py index 4b11c96beb..3d5ff68f44 100644 --- a/glance/notifier/__init__.py +++ b/glance/notifier/__init__.py @@ -183,7 +183,7 @@ class ImageProxy(glance.domain.proxy.Image): try: notify('image.send', self._format_image_send(sent)) - except Exception, err: + except Exception as err: msg = _("An error occurred during image.send" " notification: %(err)s") % locals() LOG.error(msg) @@ -193,10 +193,10 @@ class ImageProxy(glance.domain.proxy.Image): self.notifier.info('image.prepare', payload) try: self.image.set_data(data, size) - except exception.StorageFull, e: + except exception.StorageFull as e: msg = _("Image storage media is full: %s") % e self.notifier.error('image.upload', msg) - except exception.StorageWriteDenied, e: + except exception.StorageWriteDenied as e: msg = _("Insufficient permissions on image storage media: %s") % e self.notifier.error('image.upload', msg) else: diff --git a/glance/notifier/notify_kombu.py b/glance/notifier/notify_kombu.py index d8dd72a3a3..27efb6d174 100644 --- a/glance/notifier/notify_kombu.py +++ b/glance/notifier/notify_kombu.py @@ -129,9 +129,9 @@ class RabbitStrategy(strategy.Strategy): try: self._connect() return - except self.connection_errors, e: + except self.connection_errors as e: pass - except Exception, e: + except Exception as e: # NOTE(comstud): Unfortunately it's possible for amqplib # to return an error not covered by its transport # connection_errors in the case of a timeout waiting for @@ -194,9 +194,9 @@ class RabbitStrategy(strategy.Strategy): try: self._send_message(msg, routing_key) return - except self.connection_errors, e: + except self.connection_errors as e: pass - except Exception, e: + except Exception as e: # NOTE(comstud): Unfortunately it's possible for amqplib # to return an error not covered by its transport # connection_errors in the case of a timeout waiting for diff --git a/glance/registry/api/v1/images.py b/glance/registry/api/v1/images.py index 12172dff6f..5d7ba56147 100644 --- a/glance/registry/api/v1/images.py +++ b/glance/registry/api/v1/images.py @@ -70,7 +70,7 @@ class Controller(object): try: return self.db_api.image_get_all(context, filters=filters, **params) - except exception.NotFound, e: + except exception.NotFound as e: msg = _("Invalid marker. Image could not be found.") raise exc.HTTPBadRequest(explanation=msg) @@ -366,7 +366,7 @@ class Controller(object): msg = (_("Image with identifier %s already exists!") % image_id) LOG.error(msg) return exc.HTTPConflict(msg) - except exception.Invalid, e: + except exception.Invalid as e: msg = (_("Failed to add image metadata. " "Got error: %(e)s") % locals()) LOG.error(msg) @@ -405,7 +405,7 @@ class Controller(object): msg = _("Updating metadata for image %(id)s") LOG.info(msg % {'id': id}) return dict(image=make_image_dict(updated_image)) - except exception.Invalid, e: + except exception.Invalid as e: msg = (_("Failed to update image metadata. " "Got error: %(e)s") % locals()) LOG.error(msg) diff --git a/glance/registry/api/v1/members.py b/glance/registry/api/v1/members.py index 52b664fbde..e284ae9e8a 100644 --- a/glance/registry/api/v1/members.py +++ b/glance/registry/api/v1/members.py @@ -100,7 +100,7 @@ class Controller(object): # Get the membership list try: memb_list = body['memberships'] - except Exception, e: + except Exception as e: # Malformed entity... msg = _("Invalid membership association specified for " "image %(id)s") @@ -116,7 +116,7 @@ class Controller(object): datum = dict(image_id=image['id'], member=memb['member_id'], can_share=None) - except Exception, e: + except Exception as e: # Malformed entity... msg = _("Invalid membership association specified for " "image %(id)s") @@ -215,7 +215,7 @@ class Controller(object): if body: try: can_share = bool(body['member']['can_share']) - except Exception, e: + except Exception as e: # Malformed entity... msg = _("Invalid membership association specified for " "image %(id)s") @@ -295,7 +295,7 @@ class Controller(object): """ try: members = self.db_api.image_member_find(req.context, member=id) - except exception.NotFound, e: + except exception.NotFound as e: msg = _("Member %(id)s not found") LOG.info(msg % {'id': id}) msg = _("Membership could not be found.") diff --git a/glance/store/rbd.py b/glance/store/rbd.py index 108698d927..fd72a21d3d 100644 --- a/glance/store/rbd.py +++ b/glance/store/rbd.py @@ -174,7 +174,7 @@ class Store(glance.store.base.Store): self.pool = str(CONF.rbd_store_pool) self.user = str(CONF.rbd_store_user) self.conf_file = str(CONF.rbd_store_ceph_conf) - except cfg.ConfigFileValueError, e: + except cfg.ConfigFileValueError as e: reason = _("Error in store configuration: %s") % e LOG.error(reason) raise exception.BadStoreConfiguration(store_name='rbd', diff --git a/glance/store/s3.py b/glance/store/s3.py index 0291485199..8370817912 100644 --- a/glance/store/s3.py +++ b/glance/store/s3.py @@ -482,13 +482,13 @@ def create_bucket_if_missing(bucket, s3_conn): from boto.exception import S3ResponseError try: s3_conn.get_bucket(bucket) - except S3ResponseError, e: + except S3ResponseError as e: if e.status == httplib.NOT_FOUND: if CONF.s3_store_create_bucket_on_put: location = get_s3_location(CONF.s3_store_host) try: s3_conn.create_bucket(bucket, location=location) - except S3ResponseError, e: + except S3ResponseError as e: msg = (_("Failed to add bucket to S3.\n" "Got error from S3: %(e)s") % locals()) raise glance.store.BackendException(msg) diff --git a/glance/store/swift.py b/glance/store/swift.py index cbb564a66f..c016fa5d53 100644 --- a/glance/store/swift.py +++ b/glance/store/swift.py @@ -239,7 +239,7 @@ class BaseStore(glance.store.base.Store): resp_headers, resp_body = connection.get_object( container=location.container, obj=location.obj, resp_chunk_size=self.CHUNKSIZE) - except swiftclient.ClientException, e: + except swiftclient.ClientException as e: if e.http_status == httplib.NOT_FOUND: uri = location.get_uri() msg = _("Swift could not find image at URI.") @@ -392,7 +392,7 @@ class BaseStore(glance.store.base.Store): # GET /images/details return (location.get_uri(), image_size, obj_etag) - except swiftclient.ClientException, e: + except swiftclient.ClientException as e: if e.http_status == httplib.CONFLICT: raise exception.Duplicate(_("Swift already has an image at " "this location")) @@ -416,7 +416,7 @@ class BaseStore(glance.store.base.Store): headers = connection.head_object( location.container, location.obj) manifest = headers.get('x-object-manifest') - except swiftclient.ClientException, e: + except swiftclient.ClientException as e: if e.http_status != httplib.NOT_FOUND: raise if manifest: @@ -435,7 +435,7 @@ class BaseStore(glance.store.base.Store): # Delete object (or, in segmented case, the manifest) connection.delete_object(location.container, location.obj) - except swiftclient.ClientException, e: + except swiftclient.ClientException as e: if e.http_status == httplib.NOT_FOUND: uri = location.get_uri() msg = _("Swift could not find image at URI.") @@ -453,12 +453,12 @@ class BaseStore(glance.store.base.Store): """ try: connection.head_container(container) - except swiftclient.ClientException, e: + except swiftclient.ClientException as e: if e.http_status == httplib.NOT_FOUND: if CONF.swift_store_create_container_on_put: try: connection.put_container(container) - except swiftclient.ClientException, e: + except swiftclient.ClientException as e: msg = _("Failed to add container to Swift.\n" "Got error from Swift: %(e)s") % locals() raise glance.store.BackendException(msg) @@ -594,7 +594,7 @@ class MultiTenantStore(BaseStore): try: connection.post_container(location.container, headers=headers) - except swiftclient.ClientException, e: + except swiftclient.ClientException as e: if e.http_status == httplib.NOT_FOUND: uri = location.get_uri() msg = _("Swift could not find image at URI.") diff --git a/glance/tests/functional/__init__.py b/glance/tests/functional/__init__.py index 65d26d586f..b4c6f7aa39 100644 --- a/glance/tests/functional/__init__.py +++ b/glance/tests/functional/__init__.py @@ -667,7 +667,7 @@ class FunctionalTest(test_utils.BaseTestCase): s.connect(("127.0.0.1", port)) s.close() return True - except socket.error, e: + except socket.error as e: return False def wait_for_servers(self, servers, expect_launch=True, timeout=10): diff --git a/glance/tests/functional/store/test_swift.py b/glance/tests/functional/store/test_swift.py index 923c94e810..e638c68cf3 100644 --- a/glance/tests/functional/store/test_swift.py +++ b/glance/tests/functional/store/test_swift.py @@ -90,7 +90,7 @@ def swift_connect(auth_url, auth_version, user, key): def swift_list_containers(swift_conn): try: _, containers = swift_conn.get_account() - except Exception, e: + except Exception as e: msg = ("Failed to list containers (get_account) " "from Swift. Got error: %s" % e) raise SwiftStoreError(msg) @@ -101,7 +101,7 @@ def swift_list_containers(swift_conn): def swift_create_container(swift_conn, container_name): try: swift_conn.put_container(container_name) - except swiftclient.ClientException, e: + except swiftclient.ClientException as e: msg = "Failed to create container. Got error: %s" % e raise SwiftStoreError(msg) @@ -113,7 +113,7 @@ def swift_get_container(swift_conn, container_name, **kwargs): def swift_delete_container(swift_conn, container_name): try: swift_conn.delete_container(container_name) - except swiftclient.ClientException, e: + except swiftclient.ClientException as e: msg = "Failed to delete container from Swift. Got error: %s" % e raise SwiftStoreError(msg) diff --git a/glance/tests/functional/store_utils.py b/glance/tests/functional/store_utils.py index 2a92e7a46c..f2f1bfcab5 100644 --- a/glance/tests/functional/store_utils.py +++ b/glance/tests/functional/store_utils.py @@ -119,7 +119,7 @@ def setup_swift(test): else: test.__dict__[key] = value - except ConfigParser.ParsingError, e: + except ConfigParser.ParsingError as e: test.disabled_message = ("Failed to read test_swift.conf " "file. Got error: %s" % e) test.disabled = True @@ -134,7 +134,7 @@ def setup_swift(test): user = test.swift_store_user key = test.swift_store_key container_name = test.swift_store_container - except AttributeError, e: + except AttributeError as e: test.disabled_message = ("Failed to find required configuration " "options for Swift store. " "Got error: %s" % e) @@ -146,7 +146,7 @@ def setup_swift(test): try: _resp_headers, containers = swift_conn.get_account() - except Exception, e: + except Exception as e: test.disabled_message = ("Failed to get_account from Swift " "Got error: %s" % e) test.disabled = True @@ -156,7 +156,7 @@ def setup_swift(test): for container in containers: if container == container_name: swift_conn.delete_container(container) - except swiftclient.ClientException, e: + except swiftclient.ClientException as e: test.disabled_message = ("Failed to delete container from Swift " "Got error: %s" % e) test.disabled = True @@ -166,7 +166,7 @@ def setup_swift(test): try: swift_conn.put_container(container_name) - except swiftclient.ClientException, e: + except swiftclient.ClientException as e: test.disabled_message = ("Failed to create container. " "Got error: %s" % e) test.disabled = True @@ -182,7 +182,7 @@ def teardown_swift(test): for container in containers: if container.find(container_name) == 0: swift_conn.delete_container(container) - except swiftclient.ClientException, e: + except swiftclient.ClientException as e: if e.http_status == httplib.CONFLICT: pass else: @@ -219,7 +219,7 @@ def setup_s3(test): for key, value in defaults.items(): test.__dict__[key] = (_uniq(value) if key == 's3_store_bucket' else value) - except ConfigParser.ParsingError, e: + except ConfigParser.ParsingError as e: test.disabled_message = ("Failed to read test_s3.conf config " "file. Got error: %s" % e) test.disabled = True @@ -233,7 +233,7 @@ def setup_s3(test): access_key = test.s3_store_access_key secret_key = test.s3_store_secret_key bucket_name = test.s3_store_bucket - except AttributeError, e: + except AttributeError as e: test.disabled_message = ("Failed to find required configuration " "options for S3 store. Got error: %s" % e) test.disabled = True @@ -251,13 +251,13 @@ def setup_s3(test): for bucket in buckets: if bucket.name == bucket_name: test.bucket = bucket - except S3ResponseError, e: + except S3ResponseError as e: test.disabled_message = ("Failed to connect to S3 with " "credentials, to find bucket. " "Got error: %s" % e) test.disabled = True return - except TypeError, e: + except TypeError as e: # This hack is necessary because of a bug in boto 1.9b: # http://code.google.com/p/boto/issues/detail?id=540 test.disabled_message = ("Failed to connect to S3 with " @@ -272,7 +272,7 @@ def setup_s3(test): try: test.bucket = s3_conn.create_bucket(bucket_name, location=location) - except S3ResponseError, e: + except S3ResponseError as e: test.disabled_message = ("Failed to create bucket. " "Got error: %s" % e) test.disabled = True diff --git a/glance/tests/functional/v1/test_rbd.py b/glance/tests/functional/v1/test_rbd.py index 36bd6ccc8b..d6e316feee 100644 --- a/glance/tests/functional/v1/test_rbd.py +++ b/glance/tests/functional/v1/test_rbd.py @@ -67,7 +67,7 @@ class TestRBD(test_api.TestApi): defaults = cp.defaults() for key, value in defaults.items(): self.__dict__[key] = value - except ConfigParser.ParsingError, e: + except ConfigParser.ParsingError as e: self.disabled_message = ("Failed to read test_rbd config " "file. Got error: %s" % e) return @@ -81,7 +81,7 @@ class TestRBD(test_api.TestApi): rados_id=self.rbd_store_user) try: cluster.connect() - except rados.Error, e: + except rados.Error as e: self.disabled_message = ("Failed to connect to RADOS: %s" % e) return cluster.shutdown() @@ -96,7 +96,7 @@ class TestRBD(test_api.TestApi): import rados try: self.create_pool() - except rados.Error, e: + except rados.Error as e: self.disabled_message = ("Failed to create pool: %s" % e) self.disabled = True return diff --git a/glance/tests/unit/test_migrations.py b/glance/tests/unit/test_migrations.py index e9004e833a..1e87f852a2 100644 --- a/glance/tests/unit/test_migrations.py +++ b/glance/tests/unit/test_migrations.py @@ -138,7 +138,7 @@ class TestMigrations(utils.BaseTestCase): for key, value in defaults.items(): self.test_databases[key] = value self.snake_walk = cp.getboolean('walk_style', 'snake_walk') - except ConfigParser.ParsingError, e: + except ConfigParser.ParsingError as e: self.fail("Failed to read test_migrations.conf config " "file. Got error: %s" % e) else: diff --git a/glance/tests/unit/test_swift_store.py b/glance/tests/unit/test_swift_store.py index d239c9c86b..4ff5507d78 100644 --- a/glance/tests/unit/test_swift_store.py +++ b/glance/tests/unit/test_swift_store.py @@ -383,7 +383,7 @@ class SwiftTests(object): exception_caught = False try: self.store.add(uuidutils.generate_uuid(), image_swift, 0) - except BackendException, e: + except BackendException as e: exception_caught = True self.assertTrue("container noexist does not exist " "in Swift" in str(e)) diff --git a/glance/tests/utils.py b/glance/tests/utils.py index 4c553078e0..da7e552168 100644 --- a/glance/tests/utils.py +++ b/glance/tests/utils.py @@ -259,7 +259,7 @@ def xattr_writes_supported(path): fake_file.flush() try: set_xattr(fake_filepath, 'hits', '1') - except IOError, e: + except IOError as e: if e.errno == errno.EOPNOTSUPP: result = False else: