diff options
| author | Claude Paroz <claude@2xlibre.net> | 2012-04-28 18:09:37 +0200 |
|---|---|---|
| committer | Claude Paroz <claude@2xlibre.net> | 2012-04-29 20:57:15 +0200 |
| commit | 3904b74a3f2f92fefe1d39281ed683c52f2fef03 (patch) | |
| tree | 1ae8f65371ed53df205553f41c9d0f90d1e9fee9 | |
| parent | eefb00f30124f775ca52258ccd8549054fe8230f (diff) | |
Fixed #18013 -- Use the new 'as' syntax for exceptions.
Thanks Clueless for the initial patch.
Note that unittest has been purposely left out (external package only used by Python 2.6).
107 files changed, 306 insertions, 354 deletions
diff --git a/django/conf/__init__.py b/django/conf/__init__.py index 0d8f4b6b83..6a2485bd4b 100644 --- a/django/conf/__init__.py +++ b/django/conf/__init__.py @@ -91,7 +91,7 @@ class Settings(BaseSettings): try: mod = importlib.import_module(self.SETTINGS_MODULE) - except ImportError, e: + except ImportError as e: raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e)) # Settings that should be converted into tuples if they're mistakenly entered diff --git a/django/contrib/admin/tests.py b/django/contrib/admin/tests.py index 2cc8b2a92d..eaf1c8600c 100644 --- a/django/contrib/admin/tests.py +++ b/django/contrib/admin/tests.py @@ -14,7 +14,7 @@ class AdminSeleniumWebDriverTestCase(LiveServerTestCase): mod = import_module(module) WebDriver = getattr(mod, attr) cls.selenium = WebDriver() - except Exception, e: + except Exception as e: raise SkipTest('Selenium webdriver "%s" not installed or not ' 'operational: %s' % (cls.webdriver_class, str(e))) super(AdminSeleniumWebDriverTestCase, cls).setUpClass() diff --git a/django/contrib/admin/util.py b/django/contrib/admin/util.py index 0eb6791485..9611b00050 100644 --- a/django/contrib/admin/util.py +++ b/django/contrib/admin/util.py @@ -156,7 +156,7 @@ class NestedObjects(Collector): self.add_edge(None, obj) try: return super(NestedObjects, self).collect(objs, source_attr=source_attr, **kwargs) - except models.ProtectedError, e: + except models.ProtectedError as e: self.protected.update(e.protected_objects) def related_objects(self, related, objs): diff --git a/django/contrib/admin/views/main.py b/django/contrib/admin/views/main.py index 9d5c30434d..bc158da80a 100644 --- a/django/contrib/admin/views/main.py +++ b/django/contrib/admin/views/main.py @@ -139,7 +139,7 @@ class ChangeList(object): use_distinct = (use_distinct or lookup_needs_distinct(self.lookup_opts, key)) return filter_specs, bool(filter_specs), lookup_params, use_distinct - except FieldDoesNotExist, e: + except FieldDoesNotExist as e: raise IncorrectLookupParameters(e) def get_query_string(self, new_params=None, remove=None): @@ -316,7 +316,7 @@ class ChangeList(object): # Allow certain types of errors to be re-raised as-is so that the # caller can treat them in a special way. raise - except Exception, e: + except Exception as e: # Every other error is caught with a naked except, because we don't # have any other way of validating lookup parameters. They might be # invalid if the keyword arguments are incorrect, or if the values diff --git a/django/contrib/admindocs/views.py b/django/contrib/admindocs/views.py index 33d9a7da2b..aad698836e 100644 --- a/django/contrib/admindocs/views.py +++ b/django/contrib/admindocs/views.py @@ -318,7 +318,7 @@ def load_all_installed_template_libraries(): for library_name in libraries: try: lib = template.get_library(library_name) - except template.InvalidTemplateLibrary, e: + except template.InvalidTemplateLibrary: pass def get_return_data_type(func_name): diff --git a/django/contrib/auth/__init__.py b/django/contrib/auth/__init__.py index dd816ce726..0b3ccf7d8c 100644 --- a/django/contrib/auth/__init__.py +++ b/django/contrib/auth/__init__.py @@ -11,9 +11,9 @@ def load_backend(path): module, attr = path[:i], path[i+1:] try: mod = import_module(module) - except ImportError, e: + except ImportError as e: raise ImproperlyConfigured('Error importing authentication backend %s: "%s"' % (path, e)) - except ValueError, e: + except ValueError: raise ImproperlyConfigured('Error importing authentication backends. Is AUTHENTICATION_BACKENDS a correctly defined list or tuple?') try: cls = getattr(mod, attr) diff --git a/django/contrib/comments/views/comments.py b/django/contrib/comments/views/comments.py index 57720163c3..c9a11606b3 100644 --- a/django/contrib/comments/views/comments.py +++ b/django/contrib/comments/views/comments.py @@ -66,7 +66,7 @@ def post_comment(request, next=None, using=None): return CommentPostBadRequest( "No object matching content-type %r and object PK %r exists." % \ (escape(ctype), escape(object_pk))) - except (ValueError, ValidationError), e: + except (ValueError, ValidationError) as e: return CommentPostBadRequest( "Attempting go get content-type %r and object PK %r exists raised %s" % \ (escape(ctype), escape(object_pk), e.__class__.__name__)) diff --git a/django/contrib/formtools/wizard/storage/__init__.py b/django/contrib/formtools/wizard/storage/__init__.py index b88ccc79ef..f2293c93a3 100644 --- a/django/contrib/formtools/wizard/storage/__init__.py +++ b/django/contrib/formtools/wizard/storage/__init__.py @@ -10,7 +10,7 @@ def get_storage(path, *args, **kwargs): module, attr = path[:i], path[i+1:] try: mod = import_module(module) - except ImportError, e: + except ImportError as e: raise MissingStorageModule( 'Error loading storage %s: "%s"' % (module, e)) try: diff --git a/django/contrib/gis/db/backends/base.py b/django/contrib/gis/db/backends/base.py index c8bb3d2f93..26e97622a8 100644 --- a/django/contrib/gis/db/backends/base.py +++ b/django/contrib/gis/db/backends/base.py @@ -164,13 +164,13 @@ class SpatialRefSysMixin(object): try: self._srs = gdal.SpatialReference(self.wkt) return self.srs - except Exception, msg: + except Exception as msg: pass try: self._srs = gdal.SpatialReference(self.proj4text) return self.srs - except Exception, msg: + except Exception as msg: pass raise Exception('Could not get OSR SpatialReference from WKT: %s\nError:\n%s' % (self.wkt, msg)) diff --git a/django/contrib/gis/db/backends/oracle/introspection.py b/django/contrib/gis/db/backends/oracle/introspection.py index 58dd3f39b8..716f318d24 100644 --- a/django/contrib/gis/db/backends/oracle/introspection.py +++ b/django/contrib/gis/db/backends/oracle/introspection.py @@ -16,7 +16,7 @@ class OracleIntrospection(DatabaseIntrospection): cursor.execute('SELECT "DIMINFO", "SRID" FROM "USER_SDO_GEOM_METADATA" WHERE "TABLE_NAME"=%s AND "COLUMN_NAME"=%s', (table_name.upper(), geo_col.upper())) row = cursor.fetchone() - except Exception, msg: + except Exception as msg: raise Exception('Could not find entry in USER_SDO_GEOM_METADATA corresponding to "%s"."%s"\n' 'Error message: %s.' % (table_name, geo_col, msg)) diff --git a/django/contrib/gis/db/backends/postgis/operations.py b/django/contrib/gis/db/backends/postgis/operations.py index 32867484bf..964be8de0e 100644 --- a/django/contrib/gis/db/backends/postgis/operations.py +++ b/django/contrib/gis/db/backends/postgis/operations.py @@ -107,9 +107,7 @@ class PostGISOperations(DatabaseOperations, BaseSpatialOperations): 'Was the database created from a spatial database ' 'template?' % self.connection.settings_dict['NAME'] ) - except Exception, e: - # TODO: Raise helpful exceptions as they become known. - raise + # TODO: Raise helpful exceptions as they become known. # PostGIS-specific operators. The commented descriptions of these # operators come from Section 7.6 of the PostGIS 1.4 documentation. diff --git a/django/contrib/gis/db/backends/spatialite/base.py b/django/contrib/gis/db/backends/spatialite/base.py index aea52f5777..b447d1d9ff 100644 --- a/django/contrib/gis/db/backends/spatialite/base.py +++ b/django/contrib/gis/db/backends/spatialite/base.py @@ -56,7 +56,7 @@ class DatabaseWrapper(SQLiteDatabaseWrapper): cur = self.connection.cursor(factory=SQLiteCursorWrapper) try: cur.execute("SELECT load_extension(%s)", (self.spatialite_lib,)) - except Exception, msg: + except Exception as msg: raise ImproperlyConfigured('Unable to load the SpatiaLite library extension ' '"%s" because: %s' % (self.spatialite_lib, msg)) return cur diff --git a/django/contrib/gis/db/backends/spatialite/operations.py b/django/contrib/gis/db/backends/spatialite/operations.py index a0efb99527..6adcdc5275 100644 --- a/django/contrib/gis/db/backends/spatialite/operations.py +++ b/django/contrib/gis/db/backends/spatialite/operations.py @@ -122,7 +122,7 @@ class SpatiaLiteOperations(DatabaseOperations, BaseSpatialOperations): self.spatial_version = version except ImproperlyConfigured: raise - except Exception, msg: + except Exception as msg: raise ImproperlyConfigured('Cannot determine the SpatiaLite version for the "%s" ' 'database (error was "%s"). Was the SpatiaLite initialization ' 'SQL loaded on this database?' % diff --git a/django/contrib/gis/geometry/backend/__init__.py b/django/contrib/gis/geometry/backend/__init__.py index d79a5563ed..d9f30bb256 100644 --- a/django/contrib/gis/geometry/backend/__init__.py +++ b/django/contrib/gis/geometry/backend/__init__.py @@ -6,10 +6,10 @@ geom_backend = getattr(settings, 'GEOMETRY_BACKEND', 'geos') try: module = import_module('.%s' % geom_backend, 'django.contrib.gis.geometry.backend') -except ImportError, e: +except ImportError: try: module = import_module(geom_backend) - except ImportError, e_user: + except ImportError: raise ImproperlyConfigured('Could not import user-defined GEOMETRY_BACKEND ' '"%s".' % geom_backend) diff --git a/django/contrib/gis/management/commands/ogrinspect.py b/django/contrib/gis/management/commands/ogrinspect.py index fbc6f53c0c..6037cc7ea6 100644 --- a/django/contrib/gis/management/commands/ogrinspect.py +++ b/django/contrib/gis/management/commands/ogrinspect.py @@ -87,7 +87,7 @@ class Command(LabelCommand): # Getting the OGR DataSource from the string parameter. try: ds = gdal.DataSource(data_source) - except gdal.OGRException, msg: + except gdal.OGRException as msg: raise CommandError(msg) # Whether the user wants to generate the LayerMapping dictionary as well. diff --git a/django/contrib/gis/tests/test_measure.py b/django/contrib/gis/tests/test_measure.py index 8ca6be1c40..72482da353 100644 --- a/django/contrib/gis/tests/test_measure.py +++ b/django/contrib/gis/tests/test_measure.py @@ -62,32 +62,20 @@ class DistanceTest(unittest.TestCase): d4 -= d1 self.assertEqual(d4.m, -200) - try: + with self.assertRaises(TypeError): d5 = d1 + 1 - except TypeError, e: - pass - else: self.fail('Distance + number should raise TypeError') - try: + with self.assertRaises(TypeError): d5 = d1 - 1 - except TypeError, e: - pass - else: self.fail('Distance - number should raise TypeError') - try: + with self.assertRaises(TypeError): d1 += 1 - except TypeError, e: - pass - else: self.fail('Distance += number should raise TypeError') - try: + with self.assertRaises(TypeError): d1 -= 1 - except TypeError, e: - pass - else: self.fail('Distance -= number should raise TypeError') def testMultiplication(self): @@ -110,25 +98,16 @@ class DistanceTest(unittest.TestCase): self.assertTrue(isinstance(a5, Area)) self.assertEqual(a5.sq_m, 100*10) - try: + with self.assertRaises(TypeError): d1 *= D(m=1) - except TypeError, e: - pass - else: self.fail('Distance *= Distance should raise TypeError') - try: + with self.assertRaises(TypeError): d5 = d1 / D(m=1) - except TypeError, e: - pass - else: self.fail('Distance / Distance should raise TypeError') - try: + with self.assertRaises(TypeError): d1 /= D(m=1) - except TypeError, e: - pass - else: self.fail('Distance /= Distance should raise TypeError') def testUnitConversions(self): @@ -217,32 +196,20 @@ class AreaTest(unittest.TestCase): a4 -= a1 self.assertEqual(a4.sq_m, -200) - try: + with self.assertRaises(TypeError): a5 = a1 + 1 - except TypeError, e: - pass - else: self.fail('Area + number should raise TypeError') - try: + with self.assertRaises(TypeError): a5 = a1 - 1 - except TypeError, e: - pass - else: self.fail('Area - number should raise TypeError') - try: + with self.assertRaises(TypeError): a1 += 1 - except TypeError, e: - pass - else: self.fail('Area += number should raise TypeError') - try: + with self.assertRaises(TypeError): a1 -= 1 - except TypeError, e: - pass - else: self.fail('Area -= number should raise TypeError') def testMultiplication(self): @@ -261,32 +228,20 @@ class AreaTest(unittest.TestCase): a4 /= 5 self.assertEqual(a4.sq_m, 10) - try: + with self.assertRaises(TypeError): a5 = a1 * A(sq_m=1) - except TypeError, e: - pass - else: self.fail('Area * Area should raise TypeError') - try: + with self.assertRaises(TypeError): a1 *= A(sq_m=1) - except TypeError, e: - pass - else: self.fail('Area *= Area should raise TypeError') - try: + with self.assertRaises(TypeError): a5 = a1 / A(sq_m=1) - except TypeError, e: - pass - else: self.fail('Area / Area should raise TypeError') - try: + with self.assertRaises(TypeError): a1 /= A(sq_m=1) - except TypeError, e: - pass - else: self.fail('Area /= Area should raise TypeError') def testUnitConversions(self): diff --git a/django/contrib/gis/utils/layermapping.py b/django/contrib/gis/utils/layermapping.py index 154617f0b9..ea3f3d7861 100644 --- a/django/contrib/gis/utils/layermapping.py +++ b/django/contrib/gis/utils/layermapping.py @@ -430,7 +430,7 @@ class LayerMapping(object): # Creating the CoordTransform object return CoordTransform(self.source_srs, target_srs) - except Exception, msg: + except Exception as msg: raise LayerMapError('Could not translate between the data source and model geometry: %s' % msg) def geometry_field(self): @@ -514,7 +514,7 @@ class LayerMapping(object): # Getting the keyword arguments try: kwargs = self.feature_kwargs(feat) - except LayerMapError, msg: + except LayerMapError as msg: # Something borked the validation if strict: raise elif not silent: @@ -553,7 +553,7 @@ class LayerMapping(object): if verbose: stream.write('%s: %s\n' % (is_update and 'Updated' or 'Saved', m)) except SystemExit: raise - except Exception, msg: + except Exception as msg: if self.transaction_mode == 'autocommit': # Rolling back the transaction so that other model saves # will work. diff --git a/django/contrib/markup/tests.py b/django/contrib/markup/tests.py index d3e4e1db1d..7b050ace82 100644 --- a/django/contrib/markup/tests.py +++ b/django/contrib/markup/tests.py @@ -87,7 +87,7 @@ Paragraph 2 with a link_ # Docutils v0.4 and earlier self.assertEqual(rendered, """<p>Paragraph 1</p> <p>Paragraph 2 with a <a class="reference" href="http://www.example.com/">link</a></p>""") - except AssertionError, e: + except AssertionError: # Docutils from SVN (which will become 0.5) self.assertEqual(rendered, """<p>Paragraph 1</p> <p>Paragraph 2 with a <a class="reference external" href="http://www.example.com/">link</a></p>""") diff --git a/django/contrib/messages/storage/__init__.py b/django/contrib/messages/storage/__init__.py index ce3971b25c..a584acca1c 100644 --- a/django/contrib/messages/storage/__init__.py +++ b/django/contrib/messages/storage/__init__.py @@ -15,7 +15,7 @@ def get_storage(import_path): module, classname = import_path[:dot], import_path[dot + 1:] try: mod = import_module(module) - except ImportError, e: + except ImportError as e: raise ImproperlyConfigured('Error importing module %s: "%s"' % (module, e)) try: diff --git a/django/contrib/sessions/backends/file.py b/django/contrib/sessions/backends/file.py index 8ffddc4903..cb81534586 100644 --- a/django/contrib/sessions/backends/file.py +++ b/django/contrib/sessions/backends/file.py @@ -90,7 +90,7 @@ class SessionStore(SessionBase): fd = os.open(session_file_name, flags) os.close(fd) - except OSError, e: + except OSError as e: if must_create and e.errno == errno.EEXIST: raise CreateError raise diff --git a/django/contrib/staticfiles/finders.py b/django/contrib/staticfiles/finders.py index 7b4c7c8178..766687cf7d 100644 --- a/django/contrib/staticfiles/finders.py +++ b/django/contrib/staticfiles/finders.py @@ -260,7 +260,7 @@ def _get_finder(import_path): module, attr = import_path.rsplit('.', 1) try: mod = import_module(module) - except ImportError, e: + except ImportError as e: raise ImproperlyConfigured('Error importing module %s: "%s"' % (module, e)) try: diff --git a/django/contrib/staticfiles/handlers.py b/django/contrib/staticfiles/handlers.py index 962b835fef..f475b22d9c 100644 --- a/django/contrib/staticfiles/handlers.py +++ b/django/contrib/staticfiles/handlers.py @@ -56,7 +56,7 @@ class StaticFilesHandler(WSGIHandler): if self._should_handle(request.path): try: return self.serve(request) - except Http404, e: + except Http404 as e: if settings.DEBUG: from django.views import debug return debug.technical_404_response(request, e) diff --git a/django/core/cache/__init__.py b/django/core/cache/__init__.py index 8f07f13d3a..2a9e1a700b 100644 --- a/django/core/cache/__init__.py +++ b/django/core/cache/__init__.py @@ -128,7 +128,7 @@ def get_cache(backend, **kwargs): mod_path, cls_name = backend.rsplit('.', 1) mod = importlib.import_module(mod_path) backend_cls = getattr(mod, cls_name) - except (AttributeError, ImportError), e: + except (AttributeError, ImportError) as e: raise InvalidCacheBackendError( "Could not find backend '%s': %s" % (backend, e)) cache = backend_cls(location, params) diff --git a/django/core/files/move.py b/django/core/files/move.py index 3349fc22e7..4778228ccd 100644 --- a/django/core/files/move.py +++ b/django/core/files/move.py @@ -79,7 +79,7 @@ def file_move_safe(old_file_name, new_file_name, chunk_size = 1024*64, allow_ove try: os.remove(old_file_name) - except OSError, e: + except OSError as e: # Certain operating systems (Cygwin and Windows) # fail when deleting opened files, ignore it. (For the # systems where this happens, temporary files will be auto-deleted diff --git a/django/core/files/storage.py b/django/core/files/storage.py index aa62175819..6b724b4028 100644 --- a/django/core/files/storage.py +++ b/django/core/files/storage.py @@ -166,7 +166,7 @@ class FileSystemStorage(Storage): if not os.path.exists(directory): try: os.makedirs(directory) - except OSError, e: + except OSError as e: if e.errno != errno.EEXIST: raise if not os.path.isdir(directory): @@ -197,7 +197,7 @@ class FileSystemStorage(Storage): finally: locks.unlock(fd) os.close(fd) - except OSError, e: + except OSError as e: if e.errno == errno.EEXIST: # Ooops, the file exists. We need a new file name. name = self.get_available_name(name) @@ -222,7 +222,7 @@ class FileSystemStorage(Storage): if os.path.exists(name): try: os.remove(name) - except OSError, e: + except OSError as e: if e.errno != errno.ENOENT: raise @@ -273,7 +273,7 @@ def get_storage_class(import_path=None): module, classname = import_path[:dot], import_path[dot+1:] try: mod = import_module(module) - except ImportError, e: + except ImportError as e: raise ImproperlyConfigured('Error importing storage module %s: "%s"' % (module, e)) try: return getattr(mod, classname) diff --git a/django/core/files/uploadedfile.py b/django/core/files/uploadedfile.py index 5178f0bacc..1dcd9aeeb0 100644 --- a/django/core/files/uploadedfile.py +++ b/django/core/files/uploadedfile.py @@ -75,7 +75,7 @@ class TemporaryUploadedFile(UploadedFile): def close(self): try: return self.file.close() - except OSError, e: + except OSError as e: if e.errno != 2: # Means the file was moved or deleted before the tempfile # could unlink it. Still sets self.file.close_called and diff --git a/django/core/files/uploadhandler.py b/django/core/files/uploadhandler.py index 2afb79e051..4316fddf43 100644 --- a/django/core/files/uploadhandler.py +++ b/django/core/files/uploadhandler.py @@ -204,10 +204,11 @@ def load_handler(path, *args, **kwargs): module, attr = path[:i], path[i+1:] try: mod = importlib.import_module(module) - except ImportError, e: + except ImportError as e: raise ImproperlyConfigured('Error importing upload handler module %s: "%s"' % (module, e)) - except ValueError, e: - raise ImproperlyConfigured('Error importing upload handler module. Is FILE_UPLOAD_HANDLERS a correctly defined list or tuple?') + except ValueError: + raise ImproperlyConfigured('Error importing upload handler module.' + 'Is FILE_UPLOAD_HANDLERS a correctly defined list or tuple?') try: cls = getattr(mod, attr) except AttributeError: diff --git a/django/core/handlers/base.py b/django/core/handlers/base.py index a0918bfc41..4c9dfc07bc 100644 --- a/django/core/handlers/base.py +++ b/django/core/handlers/base.py @@ -43,7 +43,7 @@ class BaseHandler(object): raise exceptions.ImproperlyConfigured('%s isn\'t a middleware module' % middleware_path) try: mod = import_module(mw_module) - except ImportError, e: + except ImportError as e: raise exceptions.ImproperlyConfigured('Error importing middleware %s: "%s"' % (mw_module, e)) try: mw_class = getattr(mod, mw_classname) @@ -109,7 +109,7 @@ class BaseHandler(object): if response is None: try: response = callback(request, *callback_args, **callback_kwargs) - except Exception, e: + except Exception as e: # If the view raised an exception, run it through exception # middleware, and if the exception middleware returns a # response, use that. Otherwise, reraise the exception. @@ -135,7 +135,7 @@ class BaseHandler(object): response = middleware_method(request, response) response = response.render() - except http.Http404, e: + except http.Http404 as e: logger.warning('Not Found: %s', request.path, extra={ 'status_code': 404, diff --git a/django/core/mail/__init__.py b/django/core/mail/__init__.py index a9b651e538..1bee0cac9f 100644 --- a/django/core/mail/__init__.py +++ b/django/core/mail/__init__.py @@ -30,7 +30,7 @@ def get_connection(backend=None, fail_silently=False, **kwds): try: mod_name, klass_name = path.rsplit('.', 1) mod = import_module(mod_name) - except ImportError, e: + except ImportError as e: raise ImproperlyConfigured(('Error importing email backend module %s: "%s"' % (mod_name, e))) try: diff --git a/django/core/mail/backends/filebased.py b/django/core/mail/backends/filebased.py index 3f6b99b057..674ca32f3f 100644 --- a/django/core/mail/backends/filebased.py +++ b/django/core/mail/backends/filebased.py @@ -25,7 +25,7 @@ class EmailBackend(ConsoleEmailBackend): elif not os.path.exists(self.file_path): try: os.makedirs(self.file_path) - except OSError, err: + except OSError as err: raise ImproperlyConfigured('Could not create directory for saving email messages: %s (%s)' % (self.file_path, err)) # Make sure that self.file_path is writable. if not os.access(self.file_path, os.W_OK): diff --git a/django/core/management/__init__.py b/django/core/management/__init__.py index 8f32898834..840a3b74df 100644 --- a/django/core/management/__init__.py +++ b/django/core/management/__init__.py @@ -51,7 +51,7 @@ def find_management_module(app_name): # of the app_name but the project directory itself isn't on the path. try: f, path, descr = imp.find_module(part,path) - except ImportError,e: + except ImportError as e: if os.path.basename(os.getcwd()) != part: raise e diff --git a/django/core/management/base.py b/django/core/management/base.py index 0bd64f24b5..2a04c25228 100644 --- a/django/core/management/base.py +++ b/django/core/management/base.py @@ -214,7 +214,7 @@ class BaseCommand(object): from django.utils import translation saved_lang = translation.get_language() translation.activate('en-us') - except ImportError, e: + except ImportError as e: # If settings should be available, but aren't, # raise the error and quit. if show_traceback: @@ -240,7 +240,7 @@ class BaseCommand(object): self.stdout.write(output) if self.output_transaction: self.stdout.write('\n' + self.style.SQL_KEYWORD("COMMIT;") + '\n') - except CommandError, e: + except CommandError as e: if show_traceback: traceback.print_exc() else: @@ -297,7 +297,7 @@ class AppCommand(BaseCommand): raise CommandError('Enter at least one appname.') try: app_list = [models.get_app(app_label) for app_label in app_labels] - except (ImproperlyConfigured, ImportError), e: + except (ImproperlyConfigured, ImportError) as e: raise CommandError("%s. Are you sure your INSTALLED_APPS setting is correct?" % e) output = [] for app in app_list: diff --git a/django/core/management/commands/createcachetable.py b/django/core/management/commands/createcachetable.py index 7164d1aa76..82a126b0fa 100644 --- a/django/core/management/commands/createcachetable.py +++ b/django/core/management/commands/createcachetable.py @@ -54,7 +54,7 @@ class Command(LabelCommand): curs = connection.cursor() try: curs.execute("\n".join(full_statement)) - except DatabaseError, e: + except DatabaseError as e: self.stderr.write( self.style.ERROR("Cache table '%s' could not be created.\nThe error was: %s.\n" % (tablename, e))) diff --git a/django/core/management/commands/dumpdata.py b/django/core/management/commands/dumpdata.py index 1622929e93..71d6fa74f1 100644 --- a/django/core/management/commands/dumpdata.py +++ b/django/core/management/commands/dumpdata.py @@ -111,7 +111,7 @@ class Command(BaseCommand): try: return serializers.serialize(format, objects, indent=indent, use_natural_keys=use_natural_keys) - except Exception, e: + except Exception as e: if show_traceback: raise raise CommandError("Unable to serialize database: %s" % e) diff --git a/django/core/management/commands/flush.py b/django/core/management/commands/flush.py index 2e936840ff..ce3c6e856b 100644 --- a/django/core/management/commands/flush.py +++ b/django/core/management/commands/flush.py @@ -55,7 +55,7 @@ Are you sure you want to do this? cursor = connection.cursor() for sql in sql_list: cursor.execute(sql) - except Exception, e: + except Exception as e: transaction.rollback_unless_managed(using=db) raise CommandError("""Database %s couldn't be flushed. Possible reasons: * The database isn't running or isn't configured correctly. diff --git a/django/core/management/commands/loaddata.py b/django/core/management/commands/loaddata.py index 2f1775e271..848b63705a 100644 --- a/django/core/management/commands/loaddata.py +++ b/django/core/management/commands/loaddata.py @@ -190,7 +190,7 @@ class Command(BaseCommand): models.add(obj.object.__class__) try: obj.save(using=using) - except (DatabaseError, IntegrityError), e: + except (DatabaseError, IntegrityError) as e: msg = "Could not load %(app_label)s.%(object_name)s(pk=%(pk)s): %(error_msg)s" % { 'app_label': obj.object._meta.app_label, 'object_name': obj.object._meta.object_name, diff --git a/django/core/management/commands/runserver.py b/django/core/management/commands/runserver.py index 3007d0fd30..e6182198ec 100644 --- a/django/core/management/commands/runserver.py +++ b/django/core/management/commands/runserver.py @@ -109,7 +109,7 @@ class Command(BaseCommand): handler = self.get_handler(*args, **options) run(self.addr, int(self.port), handler, ipv6=self.use_ipv6, threading=threading) - except WSGIServerException, e: + except WSGIServerException as e: # Use helpful error messages instead of ugly tracebacks. ERRORS = { 13: "You don't have permission to access that port.", diff --git a/django/core/management/commands/syncdb.py b/django/core/management/commands/syncdb.py index b04ba4b47f..91f0aeca30 100644 --- a/django/core/management/commands/syncdb.py +++ b/django/core/management/commands/syncdb.py @@ -37,7 +37,7 @@ class Command(NoArgsCommand): for app_name in settings.INSTALLED_APPS: try: import_module('.management', app_name) - except ImportError, exc: + except ImportError as exc: # This is slightly hackish. We want to ignore ImportErrors # if the "management" module itself is missing -- but we don't # want to ignore the exception if the management module exists @@ -125,7 +125,7 @@ class Command(NoArgsCommand): try: for sql in custom_sql: cursor.execute(sql) - except Exception, e: + except Exception as e: self.stderr.write("Failed to install custom SQL for %s.%s model: %s\n" % \ (app_name, model._meta.object_name, e)) if show_traceback: @@ -150,7 +150,7 @@ class Command(NoArgsCommand): try: for sql in index_sql: cursor.execute(sql) - except Exception, e: + except Exception as e: self.stderr.write("Failed to install index for %s.%s model: %s\n" % \ (app_name, model._meta.object_name, e)) transaction.rollback_unless_managed(using=db) diff --git a/django/core/management/templates.py b/django/core/management/templates.py index b2a1226dbc..735e29ad7f 100644 --- a/django/core/management/templates.py +++ b/django/core/management/templates.py @@ -81,7 +81,7 @@ class TemplateCommand(BaseCommand): top_dir = path.join(os.getcwd(), name) try: os.makedirs(top_dir) - except OSError, e: + except OSError as e: if e.errno == errno.EEXIST: message = "'%s' already exists" % top_dir else: @@ -231,7 +231,7 @@ class TemplateCommand(BaseCommand): try: the_path, info = urllib.urlretrieve(url, path.join(tempdir, filename)) - except IOError, e: + except IOError as e: raise CommandError("couldn't download URL %s to %s: %s" % (url, filename, e)) @@ -286,7 +286,7 @@ class TemplateCommand(BaseCommand): try: archive.extract(filename, tempdir) return tempdir - except (archive.ArchiveException, IOError), e: + except (archive.ArchiveException, IOError) as e: raise CommandError("couldn't extract file %s to %s: %s" % (filename, tempdir, e)) diff --git a/django/core/serializers/json.py b/django/core/serializers/json.py index ab0cd0e590..eb9fcfbacd 100644 --- a/django/core/serializers/json.py +++ b/django/core/serializers/json.py @@ -45,7 +45,7 @@ def Deserializer(stream_or_string, **options): yield obj except GeneratorExit: raise - except Exception, e: + except Exception as e: # Map to deserializer error raise DeserializationError(e) diff --git a/django/core/serializers/pyyaml.py b/django/core/serializers/pyyaml.py index 7a508da5d7..dc884a66c7 100644 --- a/django/core/serializers/pyyaml.py +++ b/django/core/serializers/pyyaml.py @@ -57,6 +57,6 @@ def Deserializer(stream_or_string, **options): yield obj except GeneratorExit: raise - except Exception, e: + except Exception as e: # Map to deserializer error raise DeserializationError(e) diff --git a/django/core/servers/basehttp.py b/django/core/servers/basehttp.py index d538ce70e8..82c5aca149 100644 --- a/django/core/servers/basehttp.py +++ b/django/core/servers/basehttp.py @@ -48,13 +48,13 @@ def get_internal_wsgi_application(): module_name, attr = app_path.rsplit('.', 1) try: mod = import_module(module_name) - except ImportError, e: + except ImportError as e: raise ImproperlyConfigured( "WSGI application '%s' could not be loaded; " "could not import module '%s': %s" % (app_path, module_name, e)) try: app = getattr(mod, attr) - except AttributeError, e: + except AttributeError as e: raise ImproperlyConfigured( "WSGI application '%s' could not be loaded; " "can't find '%s' in module '%s': %s" @@ -118,7 +118,7 @@ class WSGIServer(simple_server.WSGIServer, object): """Override server_bind to store the server name.""" try: super(WSGIServer, self).server_bind() - except Exception, e: + except Exception as e: raise WSGIServerException(e) self.setup_environ() diff --git a/django/core/servers/fastcgi.py b/django/core/servers/fastcgi.py index 17fd609fa7..9c652a74ef 100644 --- a/django/core/servers/fastcgi.py +++ b/django/core/servers/fastcgi.py @@ -102,7 +102,7 @@ def runfastcgi(argset=[], **kwargs): try: import flup - except ImportError, e: + except ImportError as e: print >> sys.stderr, "ERROR: %s" % e print >> sys.stderr, " Unable to load the flup package. In order to run django" print >> sys.stderr, " as a FastCGI application, you will need to get flup from" diff --git a/django/core/signing.py b/django/core/signing.py index f2c79de706..cd9759e536 100644 --- a/django/core/signing.py +++ b/django/core/signing.py @@ -77,12 +77,12 @@ def get_cookie_signer(salt='django.core.signing.get_cookie_signer'): module, attr = modpath.rsplit('.', 1) try: mod = import_module(module) - except ImportError, e: + except ImportError as e: raise ImproperlyConfigured( 'Error importing cookie signer %s: "%s"' % (modpath, e)) try: Signer = getattr(mod, attr) - except AttributeError, e: + except AttributeError as e: raise ImproperlyConfigured( 'Error importing cookie signer %s: "%s"' % (modpath, e)) return Signer('django.http.cookies' + settings.SECRET_KEY, salt=salt) diff --git a/django/core/urlresolvers.py b/django/core/urlresolvers.py index 1497d43e91..aadd290c33 100644 --- a/django/core/urlresolvers.py +++ b/django/core/urlresolvers.py @@ -298,7 +298,7 @@ class RegexURLResolver(LocaleRegexProvider): for pattern in self.url_patterns: try: sub_match = pattern.resolve(new_path) - except Resolver404, e: + except Resolver404 as e: sub_tried = e.args[0].get('tried') if sub_tried is not None: tried.extend([[pattern] + t for t in sub_tried]) @@ -358,7 +358,7 @@ class RegexURLResolver(LocaleRegexProvider): raise ValueError("Don't mix *args and **kwargs in call to reverse()!") try: lookup_view = get_callable(lookup_view, True) - except (ImportError, AttributeError), e: + except (ImportError, AttributeError) as e: raise NoReverseMatch("Error importing '%s': %s." % (lookup_view, e)) possibilities = self.reverse_dict.getlist(lookup_view) prefix_norm, prefix_args = normalize(_prefix)[0] @@ -462,7 +462,7 @@ def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None, current extra, resolver = resolver.namespace_dict[ns] resolved_path.append(ns) ns_pattern = ns_pattern + extra - except KeyError, key: + except KeyError as key: if resolved_path: raise NoReverseMatch( "%s is not a registered namespace inside '%s'" % diff --git a/django/core/validators.py b/django/core/validators.py index ce8e6937fe..3d4bcc86c8 100644 --- a/django/core/validators.py +++ b/django/core/validators.py @@ -45,7 +45,7 @@ class URLValidator(RegexValidator): def __call__(self, value): try: super(URLValidator, self).__call__(value) - except ValidationError, e: + except ValidationError as e: # Trivial case failed. Try for possible IDN domain if value: value = smart_unicode(value) @@ -73,7 +73,7 @@ class EmailValidator(RegexValidator): def __call__(self, value): try: super(EmailValidator, self).__call__(value) - except ValidationError, e: + except ValidationError as e: # Trivial case failed. Try for possible IDN domain-part if value and u'@' in value: parts = value.split(u'@') diff --git a/django/db/backends/creation.py b/django/db/backends/creation.py index 75afe926fa..e672253009 100644 --- a/django/db/backends/creation.py +++ b/django/db/backends/creation.py @@ -329,7 +329,7 @@ class BaseDatabaseCreation(object): try: cursor.execute( "CREATE DATABASE %s %s" % (qn(test_database_name), suffix)) - except Exception, e: + except Exception as e: sys.stderr.write( "Got an error creating the test database: %s\n" % e) if not autoclobber: @@ -346,7 +346,7 @@ class BaseDatabaseCreation(object): cursor.execute( "CREATE DATABASE %s %s" % (qn(test_database_name), suffix)) - except Exception, e: + except Exception as e: sys.stderr.write( "Got an error recreating the test database: %s\n" % e) sys.exit(2) diff --git a/django/db/backends/mysql/base.py b/django/db/backends/mysql/base.py index 1be7998c49..ecbb02f31d 100644 --- a/django/db/backends/mysql/base.py +++ b/django/db/backends/mysql/base.py @@ -11,7 +11,7 @@ import warnings try: import MySQLdb as Database -except ImportError, e: +except ImportError as e: from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) @@ -114,29 +114,29 @@ class CursorWrapper(object): def execute(self, query, args=None): try: return self.cursor.execute(query, args) - except Database.IntegrityError, e: + except Database.IntegrityError as e: raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2] - except Database.OperationalError, e: + except Database.OperationalError as e: # Map some error codes to IntegrityError, since they seem to be # misclassified and Django would prefer the more logical place. if e[0] in self.codes_for_integrityerror: raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2] raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2] - except Database.DatabaseError, e: + except Database.DatabaseError as e: raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2] def executemany(self, query, args): try: return self.cursor.executemany(query, args) - except Database.IntegrityError, e: + except Database.IntegrityError as e: raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2] - except Database.OperationalError, e: + except Database.OperationalError as e: # Map some error codes to IntegrityError, since they seem to be # misclassified and Django would prefer the more logical place. if e[0] in self.codes_for_integrityerror: raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2] raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2] - except Database.DatabaseError, e: + except Database.DatabaseError as e: raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2] def __getattr__(self, attr): diff --git a/django/db/backends/oracle/base.py b/django/db/backends/oracle/base.py index fc02ac41b2..9c91baaca7 100644 --- a/django/db/backends/oracle/base.py +++ b/django/db/backends/oracle/base.py @@ -18,7 +18,7 @@ def _setup_environment(environ): if platform.system().upper().startswith('CYGWIN'): try: import ctypes - except ImportError, e: + except ImportError as e: from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured("Error loading ctypes: %s; " "the Oracle backend requires ctypes to " @@ -41,7 +41,7 @@ _setup_environment([ try: import cx_Oracle as Database -except ImportError, e: +except ImportError as e: from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured("Error loading cx_Oracle module: %s" % e) @@ -532,11 +532,11 @@ class DatabaseWrapper(BaseDatabaseWrapper): if self.connection is not None: try: return self.connection.commit() - except Database.IntegrityError, e: + except Database.IntegrityError as e: # In case cx_Oracle implements (now or in a future version) # raising this specific exception raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2] - except Database.DatabaseError, e: + except Database.DatabaseError as e: # cx_Oracle 5.0.4 raises a cx_Oracle.DatabaseError exception # with the following attributes and values: # code = 2091 @@ -673,9 +673,9 @@ class FormatStylePlaceholderCursor(object): self._guess_input_sizes([params]) try: return self.cursor.execute(query, self._param_generator(params)) - except Database.IntegrityError, e: + except Database.IntegrityError as e: raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2] - except Database.DatabaseError, e: + except Database.DatabaseError as e: # cx_Oracle <= 4.4.0 wrongly raises a DatabaseError for ORA-01400. if hasattr(e.args[0], 'code') and e.args[0].code == 1400 and not isinstance(e, IntegrityError): raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2] @@ -702,9 +702,9 @@ class FormatStylePlaceholderCursor(object): try: return self.cursor.executemany(query, [self._param_generator(p) for p in formatted]) - except Database.IntegrityError, e: + except Database.IntegrityError as e: raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2] - except Database.DatabaseError, e: + except Database.DatabaseError as e: # cx_Oracle <= 4.4.0 wrongly raises a DatabaseError for ORA-01400. if hasattr(e.args[0], 'code') and e.args[0].code == 1400 and not isinstance(e, IntegrityError): raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2] diff --git a/django/db/backends/oracle/creation.py b/django/db/backends/oracle/creation.py index 9e6133fc64..758c9ecd4a 100644 --- a/django/db/backends/oracle/creation.py +++ b/django/db/backends/oracle/creation.py @@ -62,7 +62,7 @@ class DatabaseCreation(BaseDatabaseCreation): if self._test_database_create(): try: self._execute_test_db_creation(cursor, parameters, verbosity) - except Exception, e: + except Exception as e: sys.stderr.write("Got an error creating the test database: %s\n" % e) if not autoclobber: confirm = raw_input("It appears the test database, %s, already exists. Type 'yes' to delete it, or 'no' to cancel: " % TEST_NAME) @@ -72,7 +72,7 @@ class DatabaseCreation(BaseDatabaseCreation): print "Destroying old test database '%s'..." % self.connection.alias self._execute_test_db_destruction(cursor, parameters, verbosity) self._execute_test_db_creation(cursor, parameters, verbosity) - except Exception, e: + except Exception as e: sys.stderr.write("Got an error recreating the test database: %s\n" % e) sys.exit(2) else: @@ -84,7 +84,7 @@ class DatabaseCreation(BaseDatabaseCreation): print "Creating test user..." try: self._create_test_user(cursor, parameters, verbosity) - except Exception, e: + except Exception as e: sys.stderr.write("Got an error creating the test user: %s\n" % e) if not autoclobber: confirm = raw_input("It appears the test user, %s, already exists. Type 'yes' to delete it, or 'no' to cancel: " % TEST_USER) @@ -96,7 +96,7 @@ class DatabaseCreation(BaseDatabaseCreation): if verbosity >= 1: print "Creating test user..." self._create_test_user(cursor, parameters, verbosity) - except Exception, e: + except Exception as e: sys.stderr.write("Got an error recreating the test user: %s\n" % e) sys.exit(2) else: @@ -197,7 +197,7 @@ class DatabaseCreation(BaseDatabaseCreation): print stmt try: cursor.execute(stmt) - except Exception, err: + except Exception as err: sys.stderr.write("Failed (%s)\n" % (err)) raise diff --git a/django/db/backends/postgresql_psycopg2/base.py b/django/db/backends/postgresql_psycopg2/base.py index 0d25129313..61be680d83 100644 --- a/django/db/backends/postgresql_psycopg2/base.py +++ b/django/db/backends/postgresql_psycopg2/base.py @@ -20,7 +20,7 @@ from django.utils.timezone import utc try: import psycopg2 as Database import psycopg2.extensions -except ImportError, e: +except ImportError as e: from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) @@ -50,17 +50,17 @@ class CursorWrapper(object): def execute(self, query, args=None): try: return self.cursor.execute(query, args) - except Database.IntegrityError, e: + except Database.IntegrityError as e: raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2] - except Database.DatabaseError, e: + except Database.DatabaseError as e: raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2] def executemany(self, query, args): try: return self.cursor.executemany(query, args) - except Database.IntegrityError, e: + except Database.IntegrityError as e: raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2] - except Database.DatabaseError, e: + except Database.DatabaseError as e: raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2] def __getattr__(self, attr): @@ -233,5 +233,5 @@ class DatabaseWrapper(BaseDatabaseWrapper): if self.connection is not None: try: return self.connection.commit() - except Database.IntegrityError, e: + except Database.IntegrityError as e: raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2] diff --git a/django/db/backends/sqlite3/base.py b/django/db/backends/sqlite3/base.py index 8f883e2dc3..7ce9dd38eb 100644 --- a/django/db/backends/sqlite3/base.py +++ b/django/db/backends/sqlite3/base.py @@ -24,9 +24,9 @@ from django.utils import timezone try: try: from pysqlite2 import dbapi2 as Database - except ImportError, e1: + except ImportError: from sqlite3 import dbapi2 as Database -except ImportError, exc: +except ImportError as exc: from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured("Error loading either pysqlite2 or sqlite3 modules (tried in that order): %s" % exc) @@ -335,18 +335,18 @@ class SQLiteCursorWrapper(Database.Cursor): query = self.convert_query(query) try: return Database.Cursor.execute(self, query, params) - except Database.IntegrityError, e: + except Database.IntegrityError as e: raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2] - except Database.DatabaseError, e: + except Database.DatabaseError as e: raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2] def executemany(self, query, param_list): query = self.convert_query(query) try: return Database.Cursor.executemany(self, query, param_list) - except Database.IntegrityError, e: + except Database.IntegrityError as e: raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2] - except Database.DatabaseError, e: + except Database.DatabaseError as e: raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2] def convert_query(self, query): diff --git a/django/db/backends/sqlite3/creation.py b/django/db/backends/sqlite3/creation.py index 5f55e3927c..9e660fa387 100644 --- a/django/db/backends/sqlite3/creation.py +++ b/django/db/backends/sqlite3/creation.py @@ -57,7 +57,7 @@ class DatabaseCreation(BaseDatabaseCreation): if autoclobber or confirm == 'yes': try: os.remove(test_database_name) - except Exception, e: + except Exception as e: sys.stderr.write("Got an error deleting the old test database: %s\n" % e) sys.exit(2) else: diff --git a/django/db/models/base.py b/django/db/models/base.py index e28add30a9..7df4f6d732 100644 --- a/django/db/models/base.py +++ b/django/db/models/base.py @@ -805,14 +805,14 @@ class Model(object): try: self.clean_fields(exclude=exclude) - except ValidationError, e: + except ValidationError as e: errors = e.update_error_dict(errors) # Form.clean() is run even if other validation fails, so do the # same with Model.clean() for consistency. try: self.clean() - except ValidationError, e: + except ValidationError as e: errors = e.update_error_dict(errors) # Run unique checks, but only for fields that passed validation. @@ -821,7 +821,7 @@ class Model(object): exclude.append(name) try: self.validate_unique(exclude=exclude) - except ValidationError, e: + except ValidationError as e: errors = e.update_error_dict(errors) if errors: @@ -846,7 +846,7 @@ class Model(object): continue try: setattr(self, f.attname, f.clean(raw_value, self)) - except ValidationError, e: + except ValidationError as e: errors[f.name] = e.messages if errors: diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py index 5a5e6cc8c3..3e97f6cb01 100644 --- a/django/db/models/fields/__init__.py +++ b/django/db/models/fields/__init__.py @@ -147,7 +147,7 @@ class Field(object): for v in self.validators: try: v(value) - except exceptions.ValidationError, e: + except exceptions.ValidationError as e: if hasattr(e, 'code') and e.code in self.error_messages: message = self.error_messages[e.code] if e.params: diff --git a/django/db/models/query.py b/django/db/models/query.py index 3d4fd17924..e3c5576690 100644 --- a/django/db/models/query.py +++ b/django/db/models/query.py @@ -206,7 +206,7 @@ class QuerySet(object): qs = self._clone() qs.query.set_limits(k, k + 1) return list(qs)[0] - except self.model.DoesNotExist, e: + except self.model.DoesNotExist as e: raise IndexError(e.args) def __and__(self, other): @@ -454,7 +454,7 @@ class QuerySet(object): obj.save(force_insert=True, using=self.db) transaction.savepoint_commit(sid, using=self.db) return obj, True - except IntegrityError, e: + except IntegrityError as e: transaction.savepoint_rollback(sid, using=self.db) exc_info = sys.exc_info() try: diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py index 3474434e56..497cdb9f60 100644 --- a/django/db/models/sql/query.py +++ b/django/db/models/sql/query.py @@ -1112,7 +1112,7 @@ class Query(object): parts, opts, alias, True, allow_many, allow_explicit_fk=True, can_reuse=can_reuse, negate=negate, process_extras=process_extras) - except MultiJoin, e: + except MultiJoin as e: self.split_exclude(filter_expr, LOOKUP_SEP.join(parts[:e.level]), can_reuse) return diff --git a/django/db/utils.py b/django/db/utils.py index 3f5b86ee12..2b6ae2cf2e 100644 --- a/django/db/utils.py +++ b/django/db/utils.py @@ -22,7 +22,7 @@ def load_backend(backend_name): # Look for a fully qualified database backend name try: return import_module('.base', backend_name) - except ImportError, e_user: + except ImportError as e_user: # The database backend wasn't found. Display a helpful error message # listing all possible (built-in) database backends. backend_dir = os.path.join(os.path.dirname(__file__), 'backends') @@ -112,7 +112,7 @@ class ConnectionRouter(object): try: module_name, klass_name = r.rsplit('.', 1) module = import_module(module_name) - except ImportError, e: + except ImportError as e: raise ImproperlyConfigured('Error importing database router %s: "%s"' % (klass_name, e)) try: router_class = getattr(module, klass_name) diff --git a/django/dispatch/dispatcher.py b/django/dispatch/dispatcher.py index ed9da57f27..0903c3a8a9 100644 --- a/django/dispatch/dispatcher.py +++ b/django/dispatch/dispatcher.py @@ -205,7 +205,7 @@ class Signal(object): for receiver in self._live_receivers(_make_id(sender)): try: response = receiver(signal=self, sender=sender, **named) - except Exception, err: + except Exception as err: responses.append((receiver, err)) else: responses.append((receiver, response)) diff --git a/django/dispatch/saferef.py b/django/dispatch/saferef.py index 1c7d16474f..364c13e43b 100644 --- a/django/dispatch/saferef.py +++ b/django/dispatch/saferef.py @@ -119,10 +119,10 @@ class BoundMethodWeakref(object): try: if callable( function ): function( self ) - except Exception, e: + except Exception as e: try: traceback.print_exc() - except AttributeError, err: + except AttributeError as err: print '''Exception during saferef %s cleanup function %s: %s'''%( self, function, e ) diff --git a/django/forms/fields.py b/django/forms/fields.py index 3cf730e152..39f8f9c846 100644 --- a/django/forms/fields.py +++ b/django/forms/fields.py @@ -132,7 +132,7 @@ class Field(object): for v in self.validators: try: v(value) - except ValidationError, e: + except ValidationError as e: if hasattr(e, 'code') and e.code in self.error_messages: message = self.error_messages[e.code] if e.params: @@ -884,7 +884,7 @@ class MultiValueField(Field): raise ValidationError(self.error_messages['required']) try: clean_data.append(field.clean(field_value)) - except ValidationError, e: + except ValidationError as e: # Collect all validation errors in a single list, which we'll # raise at the end of clean(), rather than raising a single # exception for the first error we encounter. diff --git a/django/forms/forms.py b/django/forms/forms.py index 94eb22dd9e..09663d173c 100644 --- a/django/forms/forms.py +++ b/django/forms/forms.py @@ -289,7 +289,7 @@ class BaseForm(StrAndUnicode): if hasattr(self, 'clean_%s' % name): value = getattr(self, 'clean_%s' % name)() self.cleaned_data[name] = value - except ValidationError, e: + except ValidationError as e: self._errors[name] = self.error_class(e.messages) if name in self.cleaned_data: del self.cleaned_data[name] @@ -297,7 +297,7 @@ class BaseForm(StrAndUnicode): def _clean_form(self): try: self.cleaned_data = self.clean() - except ValidationError, e: + except ValidationError as e: self._errors[NON_FIELD_ERRORS] = self.error_class(e.messages) def _post_clean(self): diff --git a/django/forms/formsets.py b/django/forms/formsets.py index dcd2f017e7..739a9d44e3 100644 --- a/django/forms/formsets.py +++ b/django/forms/formsets.py @@ -291,7 +291,7 @@ class BaseFormSet(StrAndUnicode): # Give self.clean() a chance to do cross-form validation. try: self.clean() - except ValidationError, e: + except ValidationError as e: self._non_form_errors = self.error_class(e.messages) def clean(self): diff --git a/django/forms/models.py b/django/forms/models.py index cd8f027070..ea80f8d855 100644 --- a/django/forms/models.py +++ b/django/forms/models.py @@ -324,13 +324,13 @@ class BaseModelForm(BaseForm): # Clean the model instance's fields. try: self.instance.clean_fields(exclude=exclude) - except ValidationError, e: + except ValidationError as e: self._update_errors(e.message_dict) # Call the model instance's clean method. try: self.instance.clean() - except ValidationError, e: + except ValidationError as e: self._update_errors({NON_FIELD_ERRORS: e.messages}) # Validate uniqueness if needed. @@ -345,7 +345,7 @@ class BaseModelForm(BaseForm): exclude = self._get_validation_exclusions() try: self.instance.validate_unique(exclude=exclude) - except ValidationError, e: + except ValidationError as e: self._update_errors(e.message_dict) def save(self, commit=True): diff --git a/django/forms/util.py b/django/forms/util.py index 886f08e581..6690442534 100644 --- a/django/forms/util.py +++ b/django/forms/util.py @@ -66,7 +66,7 @@ def from_current_timezone(value): current_timezone = timezone.get_current_timezone() try: return timezone.make_aware(value, current_timezone) - except Exception, e: + except Exception: raise ValidationError(_('%(datetime)s couldn\'t be interpreted ' 'in time zone %(current_timezone)s; it ' 'may be ambiguous or it may not exist.') diff --git a/django/http/__init__.py b/django/http/__init__.py index 577f1d8170..382f3c3f17 100644 --- a/django/http/__init__.py +++ b/django/http/__init__.py @@ -290,7 +290,7 @@ class HttpRequest(object): raise Exception("You cannot access body after reading from request's data stream") try: self._body = self.read() - except IOError, e: + except IOError as e: raise UnreadablePostError, e, sys.exc_traceback self._stream = StringIO(self._body) return self._body @@ -556,7 +556,7 @@ class HttpResponse(object): if isinstance(value, unicode): try: value = value.encode('us-ascii') - except UnicodeError, e: + except UnicodeError as e: e.reason += ', HTTP response headers must be in US-ASCII format' raise else: diff --git a/django/http/multipartparser.py b/django/http/multipartparser.py index 477a08c05a..024e11a09c 100644 --- a/django/http/multipartparser.py +++ b/django/http/multipartparser.py @@ -196,7 +196,7 @@ class MultiPartParser(object): # We only special-case base64 transfer encoding try: chunk = str(chunk).decode('base64') - except Exception, e: + except Exception as e: # Since this is only a chunk, any error is an unfixable error. raise MultiPartParserError("Could not decode base64 data: %r" % e) @@ -209,7 +209,7 @@ class MultiPartParser(object): # If the chunk received by the handler is None, then don't continue. break - except SkipFile, e: + except SkipFile: # Just use up the rest of this file... exhaust(field_stream) else: @@ -218,7 +218,7 @@ class MultiPartParser(object): else: # If this is neither a FIELD or a FILE, just exhaust the stream. exhaust(stream) - except StopUpload, e: + except StopUpload as e: if not e.connection_reset: exhaust(self._input_data) else: diff --git a/django/template/base.py b/django/template/base.py index f6f0027f69..16b0934aca 100644 --- a/django/template/base.py +++ b/django/template/base.py @@ -265,7 +265,7 @@ class Parser(object): self.invalid_block_tag(token, command, parse_until) try: compiled_result = compile_func(self, token) - except TemplateSyntaxError, e: + except TemplateSyntaxError as e: if not self.compile_function_error(token, e): raise self.extend_nodelist(nodelist, compiled_result, token) @@ -774,7 +774,7 @@ class Variable(object): # GOTCHA: This will also catch any TypeError # raised in the function itself. current = settings.TEMPLATE_STRING_IF_INVALID # invalid method call - except Exception, e: + except Exception as e: if getattr(e, 'silent_variable_failure', False): current = settings.TEMPLATE_STRING_IF_INVALID else: @@ -1237,7 +1237,7 @@ def import_library(taglib_module): """ try: mod = import_module(taglib_module) - except ImportError, e: + except ImportError as e: # If the ImportError is because the taglib submodule does not exist, # that's not an error that should be raised. If the submodule exists # and raised an ImportError on the attempt to load it, that we want diff --git a/django/template/context.py b/django/template/context.py index a7df61af16..81aa194447 100644 --- a/django/template/context.py +++ b/django/template/context.py @@ -150,7 +150,7 @@ def get_standard_processors(): module, attr = path[:i], path[i+1:] try: mod = import_module(module) - except ImportError, e: + except ImportError as e: raise ImproperlyConfigured('Error importing request processor module %s: "%s"' % (module, e)) try: func = getattr(mod, attr) diff --git a/django/template/debug.py b/django/template/debug.py index ba4f23dc94..61674034d6 100644 --- a/django/template/debug.py +++ b/django/template/debug.py @@ -72,7 +72,7 @@ class DebugNodeList(NodeList): def render_node(self, node, context): try: return node.render(context) - except Exception, e: + except Exception as e: if not hasattr(e, 'django_template_source'): e.django_template_source = node.source raise @@ -87,7 +87,7 @@ class DebugVariableNode(VariableNode): output = force_unicode(output) except UnicodeDecodeError: return '' - except Exception, e: + except Exception as e: if not hasattr(e, 'django_template_source'): e.django_template_source = self.source raise diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py index 3efb73cf96..55aa10d29d 100644 --- a/django/template/defaultfilters.py +++ b/django/template/defaultfilters.py @@ -892,5 +892,5 @@ def pprint(value): """A wrapper around pprint.pprint -- for debugging, really.""" try: return pformat(value) - except Exception, e: + except Exception as e: return u"Error in formatting: %s" % force_unicode(e, errors="replace") diff --git a/django/template/defaulttags.py b/django/template/defaulttags.py index f0a83d7e9a..5644c17055 100644 --- a/django/template/defaulttags.py +++ b/django/template/defaulttags.py @@ -183,7 +183,7 @@ class ForNode(Node): for node in self.nodelist_loop: try: nodelist.append(node.render(context)) - except Exception, e: + except Exception as e: if not hasattr(e, 'django_template_source'): e.django_template_source = node.source raise @@ -337,7 +337,7 @@ class SsiNode(Node): try: t = Template(output, name=filepath) return t.render(context) - except TemplateSyntaxError, e: + except TemplateSyntaxError as e: if settings.DEBUG: return "[Included template had syntax error: %s]" % e else: @@ -403,7 +403,7 @@ class URLNode(Node): url = '' try: url = reverse(view_name, args=args, kwargs=kwargs, current_app=context.current_app) - except NoReverseMatch, e: + except NoReverseMatch as e: if settings.SETTINGS_MODULE: project_name = settings.SETTINGS_MODULE.split('.')[0] try: @@ -1005,7 +1005,7 @@ def load(parser, token): try: taglib = bits[-1] lib = get_library(taglib) - except InvalidTemplateLibrary, e: + except InvalidTemplateLibrary as e: raise TemplateSyntaxError("'%s' is not a valid tag library: %s" % (taglib, e)) else: @@ -1028,7 +1028,7 @@ def load(parser, token): try: lib = get_library(taglib) parser.add_library(lib) - except InvalidTemplateLibrary, e: + except InvalidTemplateLibrary as e: raise TemplateSyntaxError("'%s' is not a valid tag library: %s" % (taglib, e)) return LoadNode() diff --git a/django/template/loader.py b/django/template/loader.py index 418501713d..b6d62cc2b0 100644 --- a/django/template/loader.py +++ b/django/template/loader.py @@ -93,11 +93,11 @@ def find_template_loader(loader): module, attr = loader.rsplit('.', 1) try: mod = import_module(module) - except ImportError, e: + except ImportError as e: raise ImproperlyConfigured('Error importing template source loader %s: "%s"' % (loader, e)) try: TemplateLoader = getattr(mod, attr) - except AttributeError, e: + except AttributeError as e: raise ImproperlyConfigured('Error importing template source loader %s: "%s"' % (loader, e)) if hasattr(TemplateLoader, 'load_template_source'): @@ -185,7 +185,7 @@ def select_template(template_name_list): for template_name in template_name_list: try: return get_template(template_name) - except TemplateDoesNotExist, e: + except TemplateDoesNotExist as e: if e.args[0] not in not_found: not_found.append(e.args[0]) continue diff --git a/django/template/loaders/app_directories.py b/django/template/loaders/app_directories.py index b0560b4121..1ddb18e06a 100644 --- a/django/template/loaders/app_directories.py +++ b/django/template/loaders/app_directories.py @@ -19,7 +19,7 @@ app_template_dirs = [] for app in settings.INSTALLED_APPS: try: mod = import_module(app) - except ImportError, e: + except ImportError as e: raise ImproperlyConfigured('ImportError %s: %s' % (app, e.args[0])) template_dir = os.path.join(os.path.dirname(mod.__file__), 'templates') if os.path.isdir(template_dir): diff --git a/django/test/_doctest.py b/django/test/_doctest.py index fe9b2f1890..af2f409e32 100644 --- a/django/test/_doctest.py +++ b/django/test/_doctest.py @@ -1626,7 +1626,7 @@ class DebugRunner(DocTestRunner): ... {}, 'foo', 'foo.py', 0) >>> try: ... runner.run(test) - ... except UnexpectedException, failure: + ... except UnexpectedException as failure: ... pass >>> failure.test is test @@ -1654,7 +1654,7 @@ class DebugRunner(DocTestRunner): >>> try: ... runner.run(test) - ... except DocTestFailure, failure: + ... except DocTestFailure as failure: ... pass DocTestFailure objects provide access to the test: @@ -2164,7 +2164,7 @@ class DocTestCase(unittest.TestCase): >>> case = DocTestCase(test) >>> try: ... case.debug() - ... except UnexpectedException, failure: + ... except UnexpectedException as failure: ... pass The UnexpectedException contains the test, the example, and @@ -2193,7 +2193,7 @@ class DocTestCase(unittest.TestCase): >>> try: ... case.debug() - ... except DocTestFailure, failure: + ... except DocTestFailure as failure: ... pass DocTestFailure objects provide access to the test: diff --git a/django/test/client.py b/django/test/client.py index 2b26335037..807b4cc55e 100644 --- a/django/test/client.py +++ b/django/test/client.py @@ -378,7 +378,7 @@ class Client(RequestFactory): try: response = self.handler(environ) - except TemplateDoesNotExist, e: + except TemplateDoesNotExist as e: # If the view raises an exception, Django will attempt to show # the 500.html template. If that template is not available, # we should ignore the error in favor of re-raising the diff --git a/django/test/testcases.py b/django/test/testcases.py index b923bde139..c9fe1b3a86 100644 --- a/django/test/testcases.py +++ b/django/test/testcases.py @@ -84,7 +84,7 @@ def restore_transaction_methods(): def assert_and_parse_html(self, html, user_msg, msg): try: dom = parse_html(html) - except HTMLParseError, e: + except HTMLParseError as e: standardMsg = u'%s\n%s' % (msg, e.msg) self.fail(self._formatMessage(user_msg, standardMsg)) return dom @@ -1035,7 +1035,7 @@ class LiveServerThread(threading.Thread): try: self.httpd = StoppableWSGIServer( (self.host, port), QuietWSGIRequestHandler) - except WSGIServerException, e: + except WSGIServerException as e: if (index + 1 < len(self.possible_ports) and e.args[0].errno == errno.EADDRINUSE): # This port is already in use, so we go on and try with @@ -1054,7 +1054,7 @@ class LiveServerThread(threading.Thread): self.httpd.set_app(handler) self.is_ready.set() self.httpd.serve_forever() - except Exception, e: + except Exception as e: self.error = e self.is_ready.set() diff --git a/django/utils/daemonize.py b/django/utils/daemonize.py index 68e5392d89..a9d5128b33 100644 --- a/django/utils/daemonize.py +++ b/django/utils/daemonize.py @@ -9,7 +9,7 @@ if os.name == 'posix': try: if os.fork() > 0: sys.exit(0) # kill off parent - except OSError, e: + except OSError as e: sys.stderr.write("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror)) sys.exit(1) os.setsid() @@ -20,7 +20,7 @@ if os.name == 'posix': try: if os.fork() > 0: os._exit(0) - except OSError, e: + except OSError as e: sys.stderr.write("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror)) os._exit(1) diff --git a/django/utils/decorators.py b/django/utils/decorators.py index 22f33a76a4..e653a736af 100644 --- a/django/utils/decorators.py +++ b/django/utils/decorators.py @@ -89,7 +89,7 @@ def make_middleware_decorator(middleware_class): return result try: response = view_func(request, *args, **kwargs) - except Exception, e: + except Exception as e: if hasattr(middleware, 'process_exception'): result = middleware.process_exception(request, e) if result is not None: diff --git a/django/utils/dictconfig.py b/django/utils/dictconfig.py index 42fbd9393a..ae797afcc5 100644 --- a/django/utils/dictconfig.py +++ b/django/utils/dictconfig.py @@ -297,21 +297,21 @@ class DictConfigurator(BaseConfigurator): level = handler_config.get('level', None) if level: handler.setLevel(_checkLevel(level)) - except StandardError, e: + except StandardError as e: raise ValueError('Unable to configure handler ' '%r: %s' % (name, e)) loggers = config.get('loggers', EMPTY_DICT) for name in loggers: try: self.configure_logger(name, loggers[name], True) - except StandardError, e: + except StandardError as e: raise ValueError('Unable to configure logger ' '%r: %s' % (name, e)) root = config.get('root', None) if root: try: self.configure_root(root, True) - except StandardError, e: + except StandardError as e: raise ValueError('Unable to configure root ' 'logger: %s' % e) else: @@ -326,7 +326,7 @@ class DictConfigurator(BaseConfigurator): try: formatters[name] = self.configure_formatter( formatters[name]) - except StandardError, e: + except StandardError as e: raise ValueError('Unable to configure ' 'formatter %r: %s' % (name, e)) # Next, do filters - they don't refer to anything else, either @@ -334,7 +334,7 @@ class DictConfigurator(BaseConfigurator): for name in filters: try: filters[name] = self.configure_filter(filters[name]) - except StandardError, e: + except StandardError as e: raise ValueError('Unable to configure ' 'filter %r: %s' % (name, e)) @@ -347,7 +347,7 @@ class DictConfigurator(BaseConfigurator): handler = self.configure_handler(handlers[name]) handler.name = name handlers[name] = handler - except StandardError, e: + except StandardError as e: raise ValueError('Unable to configure handler ' '%r: %s' % (name, e)) # Next, do loggers - they refer to handlers and filters @@ -386,7 +386,7 @@ class DictConfigurator(BaseConfigurator): existing.remove(name) try: self.configure_logger(name, loggers[name]) - except StandardError, e: + except StandardError as e: raise ValueError('Unable to configure logger ' '%r: %s' % (name, e)) @@ -409,7 +409,7 @@ class DictConfigurator(BaseConfigurator): if root: try: self.configure_root(root) - except StandardError, e: + except StandardError as e: raise ValueError('Unable to configure root ' 'logger: %s' % e) finally: @@ -421,7 +421,7 @@ class DictConfigurator(BaseConfigurator): factory = config['()'] # for use in exception handler try: result = self.configure_custom(config) - except TypeError, te: + except TypeError as te: if "'format'" not in str(te): raise #Name of parameter changed from fmt to format. @@ -451,7 +451,7 @@ class DictConfigurator(BaseConfigurator): for f in filters: try: filterer.addFilter(self.config['filters'][f]) - except StandardError, e: + except StandardError as e: raise ValueError('Unable to add filter %r: %s' % (f, e)) def configure_handler(self, config): @@ -460,7 +460,7 @@ class DictConfigurator(BaseConfigurator): if formatter: try: formatter = self.config['formatters'][formatter] - except StandardError, e: + except StandardError as e: raise ValueError('Unable to set formatter ' '%r: %s' % (formatter, e)) level = config.pop('level', None) @@ -477,7 +477,7 @@ class DictConfigurator(BaseConfigurator): 'target' in config: try: config['target'] = self.config['handlers'][config['target']] - except StandardError, e: + except StandardError as e: raise ValueError('Unable to set target handler ' '%r: %s' % (config['target'], e)) elif issubclass(klass, logging.handlers.SMTPHandler) and\ @@ -490,7 +490,7 @@ class DictConfigurator(BaseConfigurator): kwargs = dict([(k, config[k]) for k in config if valid_ident(k)]) try: result = factory(**kwargs) - except TypeError, te: + except TypeError as te: if "'stream'" not in str(te): raise #The argument name changed from strm to stream @@ -512,7 +512,7 @@ class DictConfigurator(BaseConfigurator): for h in handlers: try: logger.addHandler(self.config['handlers'][h]) - except StandardError, e: + except StandardError as e: raise ValueError('Unable to add handler %r: %s' % (h, e)) def common_logger_config(self, logger, config, incremental=False): diff --git a/django/utils/encoding.py b/django/utils/encoding.py index 36e0da2915..d9b59448a9 100644 --- a/django/utils/encoding.py +++ b/django/utils/encoding.py @@ -88,7 +88,7 @@ def force_unicode(s, encoding='utf-8', strings_only=False, errors='strict'): # errors), so that if s is a SafeString, it ends up being a # SafeUnicode at the end. s = s.decode(encoding, errors) - except UnicodeDecodeError, e: + except UnicodeDecodeError as e: if not isinstance(s, Exception): raise DjangoUnicodeDecodeError(s, *e.args) else: diff --git a/django/views/debug.py b/django/views/debug.py index b5499595a7..14a151f456 100644 --- a/django/views/debug.py +++ b/django/views/debug.py @@ -77,7 +77,7 @@ def get_exception_reporter_filter(request): modname, classname = modpath.rsplit('.', 1) try: mod = import_module(modname) - except ImportError, e: + except ImportError as e: raise ImproperlyConfigured( 'Error importing default exception reporter filter %s: "%s"' % (modpath, e)) try: diff --git a/docs/ref/models/instances.txt b/docs/ref/models/instances.txt index 1f60f43c97..8eaf946825 100644 --- a/docs/ref/models/instances.txt +++ b/docs/ref/models/instances.txt @@ -72,7 +72,7 @@ Example:: try: article.full_clean() - except ValidationError, e: + except ValidationError as e: # Do something based on the errors contained in e.message_dict. # Display them to a user, or handle them programatically. @@ -112,7 +112,7 @@ instead of to a specific field:: from django.core.exceptions import ValidationError, NON_FIELD_ERRORS try: article.full_clean() - except ValidationError, e: + except ValidationError as e: non_field_errors = e.message_dict[NON_FIELD_ERRORS] Finally, ``full_clean()`` will check any unique constraints on your model. diff --git a/extras/csrf_migration_helper.py b/extras/csrf_migration_helper.py index 94b5a20802..0e13163b4f 100755 --- a/extras/csrf_migration_helper.py +++ b/extras/csrf_migration_helper.py @@ -173,7 +173,7 @@ class Template(object): fd = open(self.absolute_filename) try: content = fd.read().decode(TEMPLATE_ENCODING) - except UnicodeDecodeError, e: + except UnicodeDecodeError as e: message = '%s in %s' % ( e[4], self.absolute_filename.encode('UTF-8', 'ignore')) raise UnicodeDecodeError(*(e.args[:4] + (message,))) diff --git a/tests/modeltests/basic/tests.py b/tests/modeltests/basic/tests.py index 14d35cc644..fc1f593c13 100644 --- a/tests/modeltests/basic/tests.py +++ b/tests/modeltests/basic/tests.py @@ -384,9 +384,9 @@ class ModelTest(TestCase): try: Article.objects.all()[0:1] & Article.objects.all()[4:5] self.fail('Should raise an AssertionError') - except AssertionError, e: + except AssertionError as e: self.assertEqual(str(e), "Cannot combine queries once a slice has been taken.") - except Exception, e: + except Exception as e: self.fail('Should raise an AssertionError, not %s' % e) # Negative slices are not supported, due to database constraints. @@ -394,15 +394,15 @@ class ModelTest(TestCase): try: Article.objects.all()[-1] self.fail('Should raise an AssertionError') - except AssertionError, e: + except AssertionError as e: self.assertEqual(str(e), "Negative indexing is not supported.") - except Exception, e: + except Exception as e: self.fail('Should raise an AssertionError, not %s' % e) error = None try: Article.objects.all()[0:-5] - except Exception, e: + except Exception as e: error = e self.assertTrue(isinstance(error, AssertionError)) self.assertEqual(str(error), "Negative indexing is not supported.") diff --git a/tests/modeltests/get_or_create/tests.py b/tests/modeltests/get_or_create/tests.py index f98f0e63d8..1e300fbb4d 100644 --- a/tests/modeltests/get_or_create/tests.py +++ b/tests/modeltests/get_or_create/tests.py @@ -60,7 +60,7 @@ class GetOrCreateTests(TestCase): # the actual traceback. Refs #16340. try: ManualPrimaryKeyTest.objects.get_or_create(id=1, data="Different") - except IntegrityError, e: + except IntegrityError as e: formatted_traceback = traceback.format_exc() self.assertIn('obj.save', formatted_traceback) diff --git a/tests/modeltests/invalid_models/tests.py b/tests/modeltests/invalid_models/tests.py index dac562c66e..dfc6199624 100644 --- a/tests/modeltests/invalid_models/tests.py +++ b/tests/modeltests/invalid_models/tests.py @@ -35,7 +35,7 @@ class InvalidModelTestCase(unittest.TestCase): try: module = load_app("modeltests.invalid_models.invalid_models") - except Exception, e: + except Exception: self.fail('Unable to load invalid model module') count = get_validation_errors(self.stdout, module) diff --git a/tests/modeltests/lookup/tests.py b/tests/modeltests/lookup/tests.py index 60ab25fc63..502e0d5f2b 100644 --- a/tests/modeltests/lookup/tests.py +++ b/tests/modeltests/lookup/tests.py @@ -468,13 +468,13 @@ class LookupTests(TestCase): try: Article.objects.filter(pub_date_year='2005').count() self.fail('FieldError not raised') - except FieldError, ex: + except FieldError as ex: self.assertEqual(str(ex), "Cannot resolve keyword 'pub_date_year' " "into field. Choices are: author, headline, id, pub_date, tag") try: Article.objects.filter(headline__starts='Article') self.fail('FieldError not raised') - except FieldError, ex: + except FieldError as ex: self.assertEqual(str(ex), "Join on field 'headline' not permitted. " "Did you misspell 'starts' for the lookup type?") diff --git a/tests/modeltests/select_for_update/tests.py b/tests/modeltests/select_for_update/tests.py index 65bc13a1f9..0587e11a3a 100644 --- a/tests/modeltests/select_for_update/tests.py +++ b/tests/modeltests/select_for_update/tests.py @@ -169,10 +169,8 @@ class SelectForUpdateTests(TransactionTestCase): people[0].name = 'Fred' people[0].save() transaction.commit() - except DatabaseError, e: + except DatabaseError as e: status.append(e) - except Exception, e: - raise finally: # This method is run in a separate thread. It uses its own # database connection. Close it without waiting for the GC. @@ -246,7 +244,7 @@ class SelectForUpdateTests(TransactionTestCase): ) ) ) - except DatabaseError, e: + except DatabaseError as e: status.append(e) finally: # This method is run in a separate thread. It uses its own diff --git a/tests/modeltests/validation/models.py b/tests/modeltests/validation/models.py index e402162b9a..1a6fdd7c16 100644 --- a/tests/modeltests/validation/models.py +++ b/tests/modeltests/validation/models.py @@ -99,6 +99,6 @@ try: class MultipleAutoFields(models.Model): auto1 = models.AutoField(primary_key=True) auto2 = models.AutoField(primary_key=True) -except AssertionError, assertion_error: +except AssertionError as assertion_error: pass # Fail silently assert str(assertion_error) == u"A model can't have more than one AutoField." diff --git a/tests/modeltests/validation/test_error_messages.py b/tests/modeltests/validation/test_error_messages.py index 4a2ad1fffa..04ad7aadf7 100644 --- a/tests/modeltests/validation/test_error_messages.py +++ b/tests/modeltests/validation/test_error_messages.py @@ -10,13 +10,13 @@ class ValidationMessagesTest(TestCase): self.assertRaises(ValidationError, f.clean, 'foo', None) try: f.clean('foo', None) - except ValidationError, e: + except ValidationError as e: self.assertEqual(e.messages, [u"'foo' value must be an integer."]) # primary_key must be True. Refs #12467. self.assertRaises(AssertionError, models.AutoField, 'primary_key', False) try: models.AutoField(primary_key=False) - except AssertionError, e: + except AssertionError as e: self.assertEqual(str(e), "AutoFields must have primary_key=True.") def test_integer_field_raises_error_message(self): @@ -24,7 +24,7 @@ class ValidationMessagesTest(TestCase): self.assertRaises(ValidationError, f.clean, 'foo', None) try: f.clean('foo', None) - except ValidationError, e: + except ValidationError as e: self.assertEqual(e.messages, [u"'foo' value must be an integer."]) def test_boolean_field_raises_error_message(self): @@ -32,7 +32,7 @@ class ValidationMessagesTest(TestCase): self.assertRaises(ValidationError, f.clean, 'foo', None) try: f.clean('foo', None) - except ValidationError, e: + except ValidationError as e: self.assertEqual(e.messages, [u"'foo' value must be either True or False."]) @@ -41,7 +41,7 @@ class ValidationMessagesTest(TestCase): self.assertRaises(ValidationError, f.clean, 'foo', None) try: f.clean('foo', None) - except ValidationError, e: + except ValidationError as e: self.assertEqual(e.messages, [u"'foo' value must be a float."]) def test_decimal_field_raises_error_message(self): @@ -49,7 +49,7 @@ class ValidationMessagesTest(TestCase): self.assertRaises(ValidationError, f.clean, 'foo', None) try: f.clean('foo', None) - except ValidationError, e: + except ValidationError as e: self.assertEqual(e.messages, [u"'foo' value must be a decimal number."]) @@ -58,7 +58,7 @@ class ValidationMessagesTest(TestCase): self.assertRaises(ValidationError, f.clean, 'foo', None) try: f.clean('foo', None) - except ValidationError, e: + except ValidationError as e: self.assertEqual(e.messages, [u"'foo' value must be either None, True or False."]) @@ -67,7 +67,7 @@ class ValidationMessagesTest(TestCase): self.assertRaises(ValidationError, f.clean, 'foo', None) try: f.clean('foo', None) - except ValidationError, e: + except ValidationError as e: self.assertEqual(e.messages, [ u"'foo' value has an invalid date format. " u"It must be in YYYY-MM-DD format."]) @@ -75,7 +75,7 @@ class ValidationMessagesTest(TestCase): self.assertRaises(ValidationError, f.clean, 'aaaa-10-10', None) try: f.clean('aaaa-10-10', None) - except ValidationError, e: + except ValidationError as e: self.assertEqual(e.messages, [ u"'aaaa-10-10' value has an invalid date format. " u"It must be in YYYY-MM-DD format."]) @@ -83,7 +83,7 @@ class ValidationMessagesTest(TestCase): self.assertRaises(ValidationError, f.clean, '2011-13-10', None) try: f.clean('2011-13-10', None) - except ValidationError, e: + except ValidationError as e: self.assertEqual(e.messages, [ u"'2011-13-10' value has the correct format (YYYY-MM-DD) " u"but it is an invalid date."]) @@ -91,7 +91,7 @@ class ValidationMessagesTest(TestCase): self.assertRaises(ValidationError, f.clean, '2011-10-32', None) try: f.clean('2011-10-32', None) - except ValidationError, e: + except ValidationError as e: self.assertEqual(e.messages, [ u"'2011-10-32' value has the correct format (YYYY-MM-DD) " u"but it is an invalid date."]) @@ -102,7 +102,7 @@ class ValidationMessagesTest(TestCase): self.assertRaises(ValidationError, f.clean, 'foo', None) try: f.clean('foo', None) - except ValidationError, e: + except ValidationError as e: self.assertEqual(e.messages, [ u"'foo' value has an invalid format. It must be " u"in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]) @@ -111,7 +111,7 @@ class ValidationMessagesTest(TestCase): self.assertRaises(ValidationError, f.clean, '2011-10-32', None) try: f.clean('2011-10-32', None) - except ValidationError, e: + except ValidationError as e: self.assertEqual(e.messages, [ u"'2011-10-32' value has the correct format " u"(YYYY-MM-DD) but it is an invalid date."]) @@ -120,7 +120,7 @@ class ValidationMessagesTest(TestCase): self.assertRaises(ValidationError, f.clean, '2011-10-32 10:10', None) try: f.clean('2011-10-32 10:10', None) - except ValidationError, e: + except ValidationError as e: self.assertEqual(e.messages, [ u"'2011-10-32 10:10' value has the correct format " u"(YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) " @@ -132,7 +132,7 @@ class ValidationMessagesTest(TestCase): self.assertRaises(ValidationError, f.clean, 'foo', None) try: f.clean('foo', None) - except ValidationError, e: + except ValidationError as e: self.assertEqual(e.messages, [ u"'foo' value has an invalid format. It must be in " u"HH:MM[:ss[.uuuuuu]] format."]) @@ -140,7 +140,7 @@ class ValidationMessagesTest(TestCase): self.assertRaises(ValidationError, f.clean, '25:50', None) try: f.clean('25:50', None) - except ValidationError, e: + except ValidationError as e: self.assertEqual(e.messages, [ u"'25:50' value has the correct format " u"(HH:MM[:ss[.uuuuuu]]) but it is an invalid time."]) diff --git a/tests/modeltests/validation/test_unique.py b/tests/modeltests/validation/test_unique.py index 497bb9d72d..8f819b9d9c 100644 --- a/tests/modeltests/validation/test_unique.py +++ b/tests/modeltests/validation/test_unique.py @@ -115,19 +115,19 @@ class PerformUniqueChecksTest(TestCase): p = FlexibleDatePost(title="Django 1.0 is released") try: p.full_clean() - except ValidationError, e: + except ValidationError: self.fail("unique_for_date checks shouldn't trigger when the associated DateField is None.") p = FlexibleDatePost(slug="Django 1.0") try: p.full_clean() - except ValidationError, e: + except ValidationError: self.fail("unique_for_year checks shouldn't trigger when the associated DateField is None.") p = FlexibleDatePost(subtitle="Finally") try: p.full_clean() - except ValidationError, e: + except ValidationError: self.fail("unique_for_month checks shouldn't trigger when the associated DateField is None.") def test_unique_errors(self): diff --git a/tests/regressiontests/app_loading/tests.py b/tests/regressiontests/app_loading/tests.py index 5173338399..0e66a5aad3 100644 --- a/tests/regressiontests/app_loading/tests.py +++ b/tests/regressiontests/app_loading/tests.py @@ -61,7 +61,7 @@ class EggLoadingTest(TestCase): self.assertRaises(ImportError, load_app, 'broken_app') try: load_app('broken_app') - except ImportError, e: + except ImportError as e: # Make sure the message is indicating the actual # problem in the broken app. self.assertTrue("modelz" in e.args[0]) diff --git a/tests/regressiontests/backends/tests.py b/tests/regressiontests/backends/tests.py index 3e675cc1ea..038f652698 100644 --- a/tests/regressiontests/backends/tests.py +++ b/tests/regressiontests/backends/tests.py @@ -569,7 +569,7 @@ class ThreadTests(TestCase): connections['default'] = main_thread_connection try: models.Person.objects.get(first_name="John", last_name="Doe") - except DatabaseError, e: + except DatabaseError as e: exceptions.append(e) t = threading.Thread(target=runner, args=[connections['default']]) t.start() @@ -607,7 +607,7 @@ class ThreadTests(TestCase): def runner2(other_thread_connection): try: other_thread_connection.close() - except DatabaseError, e: + except DatabaseError as e: exceptions.add(e) t2 = threading.Thread(target=runner2, args=[connections['default']]) t2.start() @@ -624,7 +624,7 @@ class ThreadTests(TestCase): def runner2(other_thread_connection): try: other_thread_connection.close() - except DatabaseError, e: + except DatabaseError as e: exceptions.add(e) # Enable thread sharing connections['default'].allow_thread_sharing = True diff --git a/tests/regressiontests/file_uploads/tests.py b/tests/regressiontests/file_uploads/tests.py index b6191ba033..a461ce1702 100644 --- a/tests/regressiontests/file_uploads/tests.py +++ b/tests/regressiontests/file_uploads/tests.py @@ -304,7 +304,7 @@ class FileUploadTests(TestCase): # it raises when there is an attempt to read more than the available bytes: try: client.FakePayload('a').read(2) - except Exception, reference_error: + except Exception as reference_error: pass # install the custom handler that tries to access request.POST @@ -312,12 +312,12 @@ class FileUploadTests(TestCase): try: response = self.client.post('/file_uploads/upload_errors/', post_data) - except reference_error.__class__, err: + except reference_error.__class__ as err: self.failIf( str(err) == str(reference_error), "Caught a repeated exception that'll cause an infinite loop in file uploads." ) - except Exception, err: + except Exception as err: # CustomUploadError is the error that should have been raised self.assertEqual(err.__class__, uploadhandler.CustomUploadError) @@ -374,9 +374,9 @@ class DirectoryCreationTests(unittest.TestCase): os.chmod(temp_storage.location, 0500) try: self.obj.testfile.save('foo.txt', SimpleUploadedFile('foo.txt', 'x')) - except OSError, err: + except OSError as err: self.assertEqual(err.errno, errno.EACCES) - except Exception, err: + except Exception: self.fail("OSError [Errno %s] not raised." % errno.EACCES) def test_not_a_directory(self): @@ -386,7 +386,7 @@ class DirectoryCreationTests(unittest.TestCase): fd.close() try: self.obj.testfile.save('foo.txt', SimpleUploadedFile('foo.txt', 'x')) - except IOError, err: + except IOError as err: # The test needs to be done on a specific string as IOError # is raised even without the patch (just not early enough) self.assertEqual(err.args[0], diff --git a/tests/regressiontests/forms/tests/error_messages.py b/tests/regressiontests/forms/tests/error_messages.py index 973bf22ab1..7153a3b0a6 100644 --- a/tests/regressiontests/forms/tests/error_messages.py +++ b/tests/regressiontests/forms/tests/error_messages.py @@ -13,7 +13,7 @@ class AssertFormErrorsMixin(object): try: the_callable(*args, **kwargs) self.fail("Testing the 'clean' method on %s failed to raise a ValidationError.") - except ValidationError, e: + except ValidationError as e: self.assertEqual(e.messages, expected) class FormsErrorMessagesTestCase(TestCase, AssertFormErrorsMixin): diff --git a/tests/regressiontests/forms/tests/validators.py b/tests/regressiontests/forms/tests/validators.py index cadf660ab8..a4cb324815 100644 --- a/tests/regressiontests/forms/tests/validators.py +++ b/tests/regressiontests/forms/tests/validators.py @@ -12,5 +12,5 @@ class TestFieldWithValidators(TestCase): self.assertRaises(ValidationError, field.clean, 'not int nor mail') try: field.clean('not int nor mail') - except ValidationError, e: + except ValidationError as e: self.assertEqual(2, len(e.messages)) diff --git a/tests/regressiontests/middleware/tests.py b/tests/regressiontests/middleware/tests.py index 3adb10964a..47fca03ba3 100644 --- a/tests/regressiontests/middleware/tests.py +++ b/tests/regressiontests/middleware/tests.py @@ -88,7 +88,7 @@ class CommonMiddlewareTest(TestCase): request) try: CommonMiddleware().process_request(request) - except RuntimeError, e: + except RuntimeError as e: self.assertTrue('end in a slash' in str(e)) settings.DEBUG = False @@ -202,7 +202,7 @@ class CommonMiddlewareTest(TestCase): request) try: CommonMiddleware().process_request(request) - except RuntimeError, e: + except RuntimeError as e: self.assertTrue('end in a slash' in str(e)) settings.DEBUG = False diff --git a/tests/regressiontests/middleware_exceptions/tests.py b/tests/regressiontests/middleware_exceptions/tests.py index ac5f09a0a8..586aa0f004 100644 --- a/tests/regressiontests/middleware_exceptions/tests.py +++ b/tests/regressiontests/middleware_exceptions/tests.py @@ -118,13 +118,13 @@ class BaseMiddlewareExceptionTest(TestCase): def assert_exceptions_handled(self, url, errors, extra_error=None): try: response = self.client.get(url) - except TestException, e: + except TestException: # Test client intentionally re-raises any exceptions being raised # during request handling. Hence actual testing that exception was # properly handled is done by relying on got_request_exception # signal being sent. pass - except Exception, e: + except Exception as e: if type(extra_error) != type(e): self.fail("Unexpected exception: %s" % e) self.assertEqual(len(self.exceptions), len(errors)) diff --git a/tests/regressiontests/model_fields/tests.py b/tests/regressiontests/model_fields/tests.py index 8fe67fb606..ea1e1c7d99 100644 --- a/tests/regressiontests/model_fields/tests.py +++ b/tests/regressiontests/model_fields/tests.py @@ -44,7 +44,7 @@ class BasicFieldTests(test.TestCase): nullboolean = NullBooleanModel(nbfield=None) try: nullboolean.full_clean() - except ValidationError, e: + except ValidationError as e: self.fail("NullBooleanField failed validation with value of None: %s" % e.messages) def test_field_repr(self): diff --git a/tests/regressiontests/model_forms_regress/tests.py b/tests/regressiontests/model_forms_regress/tests.py index caf24d336c..09da9737a8 100644 --- a/tests/regressiontests/model_forms_regress/tests.py +++ b/tests/regressiontests/model_forms_regress/tests.py @@ -333,7 +333,7 @@ class InvalidFieldAndFactory(TestCase): class Meta: model = Person fields = ('name', 'no-field') - except FieldError, e: + except FieldError as e: # Make sure the exception contains some reference to the # field responsible for the problem. self.assertTrue('no-field' in e.args[0]) diff --git a/tests/regressiontests/servers/tests.py b/tests/regressiontests/servers/tests.py index 3a72550011..c3def15771 100644 --- a/tests/regressiontests/servers/tests.py +++ b/tests/regressiontests/servers/tests.py @@ -102,7 +102,7 @@ class LiveServerViews(LiveServerBase): """ try: self.urlopen('/') - except urllib2.HTTPError, err: + except urllib2.HTTPError as err: self.assertEquals(err.code, 404, 'Expected 404 response') else: self.fail('Expected 404 response') diff --git a/tests/regressiontests/settings_tests/tests.py b/tests/regressiontests/settings_tests/tests.py index 1dbd5bd849..493ee8021d 100644 --- a/tests/regressiontests/settings_tests/tests.py +++ b/tests/regressiontests/settings_tests/tests.py @@ -62,7 +62,7 @@ class ClassDecoratedTestCase(ClassDecoratedTestCaseSuper): """ try: super(ClassDecoratedTestCase, self).test_max_recursion_error() - except RuntimeError, e: + except RuntimeError: self.fail() diff --git a/tests/regressiontests/templates/nodelist.py b/tests/regressiontests/templates/nodelist.py index b78653683f..97aa5af6a7 100644 --- a/tests/regressiontests/templates/nodelist.py +++ b/tests/regressiontests/templates/nodelist.py @@ -52,7 +52,7 @@ class ErrorIndexTest(TestCase): template = get_template_from_string(source) try: template.render(context) - except (RuntimeError, TypeError), e: + except (RuntimeError, TypeError) as e: error_source_index = e.django_template_source[1] self.assertEqual(error_source_index, expected_error_source_index) diff --git a/tests/regressiontests/templates/tests.py b/tests/regressiontests/templates/tests.py index 9b6f8d40a4..7de27a08a9 100644 --- a/tests/regressiontests/templates/tests.py +++ b/tests/regressiontests/templates/tests.py @@ -41,7 +41,7 @@ from .response import (TemplateResponseTest, CacheMiddlewareTest, try: from .loaders import RenderToStringTest, EggLoaderTest -except ImportError, e: +except ImportError as e: if "pkg_resources" in e.message: pass # If setuptools isn't installed, that's fine. Just move on. else: @@ -274,7 +274,7 @@ class Templates(unittest.TestCase): try: tmpl = loader.select_template([load_name]) r = tmpl.render(template.Context({})) - except template.TemplateDoesNotExist, e: + except template.TemplateDoesNotExist as e: settings.TEMPLATE_DEBUG = old_td self.assertEqual(e.args[0], 'missing.html') self.assertEqual(r, None, 'Template rendering unexpectedly succeeded, produced: ->%r<-' % r) @@ -307,7 +307,7 @@ class Templates(unittest.TestCase): r = None try: r = tmpl.render(template.Context({})) - except template.TemplateDoesNotExist, e: + except template.TemplateDoesNotExist as e: settings.TEMPLATE_DEBUG = old_td self.assertEqual(e.args[0], 'missing.html') self.assertEqual(r, None, 'Template rendering unexpectedly succeeded, produced: ->%r<-' % r) @@ -334,7 +334,7 @@ class Templates(unittest.TestCase): r = None try: r = tmpl.render(template.Context({})) - except template.TemplateDoesNotExist, e: + except template.TemplateDoesNotExist as e: self.assertEqual(e.args[0], 'missing.html') self.assertEqual(r, None, 'Template rendering unexpectedly succeeded, produced: ->%r<-' % r) @@ -343,7 +343,7 @@ class Templates(unittest.TestCase): tmpl = loader.get_template(load_name) try: tmpl.render(template.Context({})) - except template.TemplateDoesNotExist, e: + except template.TemplateDoesNotExist as e: self.assertEqual(e.args[0], 'missing.html') self.assertEqual(r, None, 'Template rendering unexpectedly succeeded, produced: ->%r<-' % r) finally: @@ -384,7 +384,7 @@ class Templates(unittest.TestCase): from django.template import Template, TemplateSyntaxError try: t = Template("{% if 1 %}lala{% endblock %}{% endif %}") - except TemplateSyntaxError, e: + except TemplateSyntaxError as e: self.assertEqual(e.args[0], "Invalid block tag: 'endblock', expected 'elif', 'else' or 'endif'") def test_templates(self): @@ -1638,7 +1638,7 @@ class TemplateTagLoading(unittest.TestCase): self.assertRaises(template.TemplateSyntaxError, template.Template, ttext) try: template.Template(ttext) - except template.TemplateSyntaxError, e: + except template.TemplateSyntaxError as e: self.assertTrue('ImportError' in e.args[0]) self.assertTrue('Xtemplate' in e.args[0]) @@ -1650,7 +1650,7 @@ class TemplateTagLoading(unittest.TestCase): self.assertRaises(template.TemplateSyntaxError, template.Template, ttext) try: template.Template(ttext) - except template.TemplateSyntaxError, e: + except template.TemplateSyntaxError as e: self.assertTrue('ImportError' in e.args[0]) self.assertTrue('Xtemplate' in e.args[0]) diff --git a/tests/regressiontests/test_client_regress/models.py b/tests/regressiontests/test_client_regress/models.py index f75e6458d1..ab4e592239 100644 --- a/tests/regressiontests/test_client_regress/models.py +++ b/tests/regressiontests/test_client_regress/models.py @@ -38,83 +38,83 @@ class AssertContainsTests(TestCase): try: self.assertContains(response, 'text', status_code=999) - except AssertionError, e: + except AssertionError as e: self.assertIn("Couldn't retrieve content: Response code was 200 (expected 999)", str(e)) try: self.assertContains(response, 'text', status_code=999, msg_prefix='abc') - except AssertionError, e: + except AssertionError as e: self.assertIn("abc: Couldn't retrieve content: Response code was 200 (expected 999)", str(e)) try: self.assertNotContains(response, 'text', status_code=999) - except AssertionError, e: + except AssertionError as e: self.assertIn("Couldn't retrieve content: Response code was 200 (expected 999)", str(e)) try: self.assertNotContains(response, 'text', status_code=999, msg_prefix='abc') - except AssertionError, e: + except AssertionError as e: self.assertIn("abc: Couldn't retrieve content: Response code was 200 (expected 999)", str(e)) try: self.assertNotContains(response, 'once') - except AssertionError, e: + except AssertionError as e: self.assertIn("Response should not contain 'once'", str(e)) try: self.assertNotContains(response, 'once', msg_prefix='abc') - except AssertionError, e: + except AssertionError as e: self.assertIn("abc: Response should not contain 'once'", str(e)) try: self.assertContains(response, 'never', 1) - except AssertionError, e: + except AssertionError as e: self.assertIn("Found 0 instances of 'never' in response (expected 1)", str(e)) try: self.assertContains(response, 'never', 1, msg_prefix='abc') - except AssertionError, e: + except AssertionError as e: self.assertIn("abc: Found 0 instances of 'never' in response (expected 1)", str(e)) try: self.assertContains(response, 'once', 0) - except AssertionError, e: + except AssertionError as e: self.assertIn("Found 1 instances of 'once' in response (expected 0)", str(e)) try: self.assertContains(response, 'once', 0, msg_prefix='abc') - except AssertionError, e: + except AssertionError as e: self.assertIn("abc: Found 1 instances of 'once' in response (expected 0)", str(e)) try: self.assertContains(response, 'once', 2) - except AssertionError, e: + except AssertionError as e: self.assertIn("Found 1 instances of 'once' in response (expected 2)", str(e)) try: self.assertContains(response, 'once', 2, msg_prefix='abc') - except AssertionError, e: + except AssertionError as e: self.assertIn("abc: Found 1 instances of 'once' in response (expected 2)", str(e)) try: self.assertContains(response, 'twice', 1) - except AssertionError, e: + except AssertionError as e: self.assertIn("Found 2 instances of 'twice' in response (expected 1)", str(e)) try: self.assertContains(response, 'twice', 1, msg_prefix='abc') - except AssertionError, e: + except AssertionError as e: self.assertIn("abc: Found 2 instances of 'twice' in response (expected 1)", str(e)) try: self.assertContains(response, 'thrice') - except AssertionError, e: + except AssertionError as e: self.assertIn("Couldn't find 'thrice' in response", str(e)) try: self.assertContains(response, 'thrice', msg_prefix='abc') - except AssertionError, e: + except AssertionError as e: self.assertIn("abc: Couldn't find 'thrice' in response", str(e)) try: self.assertContains(response, 'thrice', 3) - except AssertionError, e: + except AssertionError as e: self.assertIn("Found 0 instances of 'thrice' in response (expected 3)", str(e)) try: self.assertContains(response, 'thrice', 3, msg_prefix='abc') - except AssertionError, e: + except AssertionError as e: self.assertIn("abc: Found 0 instances of 'thrice' in response (expected 3)", str(e)) def test_unicode_contains(self): @@ -175,12 +175,12 @@ class AssertTemplateUsedTests(TestCase): try: self.assertTemplateUsed(response, 'GET Template') - except AssertionError, e: + except AssertionError as e: self.assertIn("No templates used to render the response", str(e)) try: self.assertTemplateUsed(response, 'GET Template', msg_prefix='abc') - except AssertionError, e: + except AssertionError as e: self.assertIn("abc: No templates used to render the response", str(e)) def test_single_context(self): @@ -189,22 +189,22 @@ class AssertTemplateUsedTests(TestCase): try: self.assertTemplateNotUsed(response, 'Empty GET Template') - except AssertionError, e: + except AssertionError as e: self.assertIn("Template 'Empty GET Template' was used unexpectedly in rendering the response", str(e)) try: self.assertTemplateNotUsed(response, 'Empty GET Template', msg_prefix='abc') - except AssertionError, e: + except AssertionError as e: self.assertIn("abc: Template 'Empty GET Template' was used unexpectedly in rendering the response", str(e)) try: self.assertTemplateUsed(response, 'Empty POST Template') - except AssertionError, e: + except AssertionError as e: self.assertIn("Template 'Empty POST Template' was not a template used to render the response. Actual template(s) used: Empty GET Template", str(e)) try: self.assertTemplateUsed(response, 'Empty POST Template', msg_prefix='abc') - except AssertionError, e: + except AssertionError as e: self.assertIn("abc: Template 'Empty POST Template' was not a template used to render the response. Actual template(s) used: Empty GET Template", str(e)) def test_multiple_context(self): @@ -220,17 +220,17 @@ class AssertTemplateUsedTests(TestCase): self.assertContains(response, 'POST data OK') try: self.assertTemplateNotUsed(response, "form_view.html") - except AssertionError, e: + except AssertionError as e: self.assertIn("Template 'form_view.html' was used unexpectedly in rendering the response", str(e)) try: self.assertTemplateNotUsed(response, 'base.html') - except AssertionError, e: + except AssertionError as e: self.assertIn("Template 'base.html' was used unexpectedly in rendering the response", str(e)) try: self.assertTemplateUsed(response, "Valid POST Template") - except AssertionError, e: + except AssertionError as e: self.assertIn("Template 'Valid POST Template' was not a template used to render the response. Actual template(s) used: form_view.html, base.html", str(e)) class AssertRedirectsTests(TestCase): @@ -240,12 +240,12 @@ class AssertRedirectsTests(TestCase): response = self.client.get('/test_client/permanent_redirect_view/') try: self.assertRedirects(response, '/test_client/get_view/') - except AssertionError, e: + except AssertionError as e: self.assertIn("Response didn't redirect as expected: Response code was 301 (expected 302)", str(e)) try: self.assertRedirects(response, '/test_client/get_view/', msg_prefix='abc') - except AssertionError, e: + except AssertionError as e: self.assertIn("abc: Response didn't redirect as expected: Response code was 301 (expected 302)", str(e)) def test_lost_query(self): @@ -253,12 +253,12 @@ class AssertRedirectsTests(TestCase): response = self.client.get('/test_client/redirect_view/', {'var': 'value'}) try: self.assertRedirects(response, '/test_client/get_view/') - except AssertionError, e: + except AssertionError as e: self.assertIn("Response redirected to 'http://testserver/test_client/get_view/?var=value', expected 'http://testserver/test_client/get_view/'", str(e)) try: self.assertRedirects(response, '/test_client/get_view/', msg_prefix='abc') - except AssertionError, e: + except AssertionError as e: self.assertIn("abc: Response redirected to 'http://testserver/test_client/get_view/?var=value', expected 'http://testserver/test_client/get_view/'", str(e)) def test_incorrect_target(self): @@ -267,7 +267,7 @@ class AssertRedirectsTests(TestCase): try: # Should redirect to get_view self.assertRedirects(response, '/test_client/some_view/') - except AssertionError, e: + except AssertionError as e: self.assertIn("Response didn't redirect as expected: Response code was 301 (expected 302)", str(e)) def test_target_page(self): @@ -276,13 +276,13 @@ class AssertRedirectsTests(TestCase): try: # The redirect target responds with a 301 code, not 200 self.assertRedirects(response, 'http://testserver/test_client/permanent_redirect_view/') - except AssertionError, e: + except AssertionError as e: self.assertIn("Couldn't retrieve redirection page '/test_client/permanent_redirect_view/': response code was 301 (expected 200)", str(e)) try: # The redirect target responds with a 301 code, not 200 self.assertRedirects(response, 'http://testserver/test_client/permanent_redirect_view/', msg_prefix='abc') - except AssertionError, e: + except AssertionError as e: self.assertIn("abc: Couldn't retrieve redirection page '/test_client/permanent_redirect_view/': response code was 301 (expected 200)", str(e)) def test_redirect_chain(self): @@ -385,12 +385,12 @@ class AssertRedirectsTests(TestCase): response = self.client.get('/test_client/get_view/', follow=True) try: self.assertRedirects(response, '/test_client/get_view/') - except AssertionError, e: + except AssertionError as e: self.assertIn("Response didn't redirect as expected: Response code was 200 (expected 302)", str(e)) try: self.assertRedirects(response, '/test_client/get_view/', msg_prefix='abc') - except AssertionError, e: + except AssertionError as e: self.assertIn("abc: Response didn't redirect as expected: Response code was 200 (expected 302)", str(e)) def test_redirect_on_non_redirect_page(self): @@ -399,12 +399,12 @@ class AssertRedirectsTests(TestCase): response = self.client.get('/test_client/get_view/') try: self.assertRedirects(response, '/test_client/get_view/') - except AssertionError, e: + except AssertionError as e: self.assertIn("Response didn't redirect as expected: Response code was 200 (expected 302)", str(e)) try: self.assertRedirects(response, '/test_client/get_view/', msg_prefix='abc') - except AssertionError, e: + except AssertionError as e: self.assertIn("abc: Response didn't redirect as expected: Response code was 200 (expected 302)", str(e)) @@ -424,11 +424,11 @@ class AssertFormErrorTests(TestCase): try: self.assertFormError(response, 'wrong_form', 'some_field', 'Some error.') - except AssertionError, e: + except AssertionError as e: self.assertIn("The form 'wrong_form' was not used to render the response", str(e)) try: self.assertFormError(response, 'wrong_form', 'some_field', 'Some error.', msg_prefix='abc') - except AssertionError, e: + except AssertionError as e: self.assertIn("abc: The form 'wrong_form' was not used to render the response", str(e)) def test_unknown_field(self): @@ -446,11 +446,11 @@ class AssertFormErrorTests(TestCase): try: self.assertFormError(response, 'form', 'some_field', 'Some error.') - except AssertionError, e: + except AssertionError as e: self.assertIn("The form 'form' in context 0 does not contain the field 'some_field'", str(e)) try: self.assertFormError(response, 'form', 'some_field', 'Some error.', msg_prefix='abc') - except AssertionError, e: + except AssertionError as e: self.assertIn("abc: The form 'form' in context 0 does not contain the field 'some_field'", str(e)) def test_noerror_field(self): @@ -468,11 +468,11 @@ class AssertFormErrorTests(TestCase): try: self.assertFormError(response, 'form', 'value', 'Some error.') - except AssertionError, e: + except AssertionError as e: self.assertIn("The field 'value' on form 'form' in context 0 contains no errors", str(e)) try: self.assertFormError(response, 'form', 'value', 'Some error.', msg_prefix='abc') - except AssertionError, e: + except AssertionError as e: self.assertIn("abc: The field 'value' on form 'form' in context 0 contains no errors", str(e)) def test_unknown_error(self): @@ -490,11 +490,11 @@ class AssertFormErrorTests(TestCase): try: self.assertFormError(response, 'form', 'email', 'Some error.') - except AssertionError, e: + except AssertionError as e: self.assertIn("The field 'email' on form 'form' in context 0 does not contain the error 'Some error.' (actual errors: [u'Enter a valid e-mail address.'])", str(e)) try: self.assertFormError(response, 'form', 'email', 'Some error.', msg_prefix='abc') - except AssertionError, e: + except AssertionError as e: self.assertIn("abc: The field 'email' on form 'form' in context 0 does not contain the error 'Some error.' (actual errors: [u'Enter a valid e-mail address.'])", str(e)) def test_unknown_nonfield_error(self): @@ -515,11 +515,11 @@ class AssertFormErrorTests(TestCase): try: self.assertFormError(response, 'form', None, 'Some error.') - except AssertionError, e: + except AssertionError as e: self.assertIn("The form 'form' in context 0 does not contain the non-field error 'Some error.' (actual errors: )", str(e)) try: self.assertFormError(response, 'form', None, 'Some error.', msg_prefix='abc') - except AssertionError, e: + except AssertionError as e: self.assertIn("abc: The form 'form' in context 0 does not contain the non-field error 'Some error.' (actual errors: )", str(e)) class LoginTests(TestCase): @@ -676,7 +676,7 @@ class ContextTests(TestCase): try: response.context['does-not-exist'] self.fail('Should not be able to retrieve non-existent key') - except KeyError, e: + except KeyError as e: self.assertEqual(e.args[0], 'does-not-exist') def test_inherited_context(self): @@ -692,7 +692,7 @@ class ContextTests(TestCase): try: response.context['does-not-exist'] self.fail('Should not be able to retrieve non-existent key') - except KeyError, e: + except KeyError as e: self.assertEqual(e.args[0], 'does-not-exist') def test_15368(self): diff --git a/tests/regressiontests/urlpatterns_reverse/tests.py b/tests/regressiontests/urlpatterns_reverse/tests.py index a1c9244918..bb25806830 100644 --- a/tests/regressiontests/urlpatterns_reverse/tests.py +++ b/tests/regressiontests/urlpatterns_reverse/tests.py @@ -161,7 +161,7 @@ class URLPatternReverse(TestCase): for name, expected, args, kwargs in test_data: try: got = reverse(name, args=args, kwargs=kwargs) - except NoReverseMatch, e: + except NoReverseMatch: self.assertEqual(expected, NoReverseMatch) else: self.assertEqual(got, expected) @@ -207,7 +207,7 @@ class ResolverTests(unittest.TestCase): try: resolve('/included/non-existent-url', urlconf=urls) self.fail('resolve did not raise a 404') - except Resolver404, e: + except Resolver404 as e: # make sure we at least matched the root ('/') url resolver: self.assertTrue('tried' in e.args[0]) tried = e.args[0]['tried'] |
