Ticket #18013: except_as_noutils.diff

File except_as_noutils.diff, 129.4 KB (added by Alex Ogier, 12 years ago)

Same without modifying utils/simplejson or utils/unittest

  • django/conf/__init__.py

    diff --git a/django/conf/__init__.py b/django/conf/__init__.py
    index a3f7ee0..8439f0f 100644
    a b class Settings(BaseSettings):  
    9191
    9292        try:
    9393            mod = importlib.import_module(self.SETTINGS_MODULE)
    94         except ImportError, e:
     94        except ImportError as e:
    9595            raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))
    9696
    9797        # Settings that should be converted into tuples if they're mistakenly entered
  • django/contrib/admin/tests.py

    diff --git a/django/contrib/admin/tests.py b/django/contrib/admin/tests.py
    index 2491fc6..59fa9ba 100644
    a b class AdminSeleniumWebDriverTestCase(LiveServerTestCase):  
    1818            mod = import_module(module)
    1919            WebDriver = getattr(mod, attr)
    2020            cls.selenium = WebDriver()
    21         except Exception, e:
     21        except Exception as e:
    2222            raise SkipTest('Selenium webdriver "%s" not installed or not '
    2323                           'operational: %s' % (cls.webdriver_class, str(e)))
    2424        super(AdminSeleniumWebDriverTestCase, cls).setUpClass()
  • django/contrib/admin/util.py

    diff --git a/django/contrib/admin/util.py b/django/contrib/admin/util.py
    index 61182a6..b1670cb 100644
    a b class NestedObjects(Collector):  
    153153                self.add_edge(None, obj)
    154154        try:
    155155            return super(NestedObjects, self).collect(objs, source_attr=source_attr, **kwargs)
    156         except models.ProtectedError, e:
     156        except models.ProtectedError as e:
    157157            self.protected.update(e.protected_objects)
    158158
    159159    def related_objects(self, related, objs):
  • django/contrib/admin/views/main.py

    diff --git a/django/contrib/admin/views/main.py b/django/contrib/admin/views/main.py
    index b11f9d5..a250315 100644
    a b class ChangeList(object):  
    139139                use_distinct = (use_distinct or
    140140                                lookup_needs_distinct(self.lookup_opts, key))
    141141            return filter_specs, bool(filter_specs), lookup_params, use_distinct
    142         except FieldDoesNotExist, e:
     142        except FieldDoesNotExist as e:
    143143            raise IncorrectLookupParameters(e)
    144144
    145145    def get_query_string(self, new_params=None, remove=None):
    class ChangeList(object):  
    316316            # Allow certain types of errors to be re-raised as-is so that the
    317317            # caller can treat them in a special way.
    318318            raise
    319         except Exception, e:
     319        except Exception as e:
    320320            # Every other error is caught with a naked except, because we don't
    321321            # have any other way of validating lookup parameters. They might be
    322322            # invalid if the keyword arguments are incorrect, or if the values
  • django/contrib/admindocs/views.py

    diff --git a/django/contrib/admindocs/views.py b/django/contrib/admindocs/views.py
    index 33d9a7d..c3405a7 100644
    a b def load_all_installed_template_libraries():  
    318318        for library_name in libraries:
    319319            try:
    320320                lib = template.get_library(library_name)
    321             except template.InvalidTemplateLibrary, e:
     321            except template.InvalidTemplateLibrary as e:
    322322                pass
    323323
    324324def get_return_data_type(func_name):
  • django/contrib/auth/__init__.py

    diff --git a/django/contrib/auth/__init__.py b/django/contrib/auth/__init__.py
    index 3495e16..93fd441 100644
    a b def load_backend(path):  
    1212    module, attr = path[:i], path[i+1:]
    1313    try:
    1414        mod = import_module(module)
    15     except ImportError, e:
     15    except ImportError as e:
    1616        raise ImproperlyConfigured('Error importing authentication backend %s: "%s"' % (path, e))
    17     except ValueError, e:
     17    except ValueError as e:
    1818        raise ImproperlyConfigured('Error importing authentication backends. Is AUTHENTICATION_BACKENDS a correctly defined list or tuple?')
    1919    try:
    2020        cls = getattr(mod, attr)
  • django/contrib/comments/views/comments.py

    diff --git a/django/contrib/comments/views/comments.py b/django/contrib/comments/views/comments.py
    index 5772016..c9a1160 100644
    a b def post_comment(request, next=None, using=None):  
    6666        return CommentPostBadRequest(
    6767            "No object matching content-type %r and object PK %r exists." % \
    6868                (escape(ctype), escape(object_pk)))
    69     except (ValueError, ValidationError), e:
     69    except (ValueError, ValidationError) as e:
    7070        return CommentPostBadRequest(
    7171            "Attempting go get content-type %r and object PK %r exists raised %s" % \
    7272                (escape(ctype), escape(object_pk), e.__class__.__name__))
  • django/contrib/formtools/wizard/storage/__init__.py

    diff --git a/django/contrib/formtools/wizard/storage/__init__.py b/django/contrib/formtools/wizard/storage/__init__.py
    index b88ccc7..f2293c9 100644
    a b def get_storage(path, *args, **kwargs):  
    1010    module, attr = path[:i], path[i+1:]
    1111    try:
    1212        mod = import_module(module)
    13     except ImportError, e:
     13    except ImportError as e:
    1414        raise MissingStorageModule(
    1515            'Error loading storage %s: "%s"' % (module, e))
    1616    try:
  • django/contrib/gis/db/backends/base.py

    diff --git a/django/contrib/gis/db/backends/base.py b/django/contrib/gis/db/backends/base.py
    index c8bb3d2..26e9762 100644
    a b class SpatialRefSysMixin(object):  
    164164                try:
    165165                    self._srs = gdal.SpatialReference(self.wkt)
    166166                    return self.srs
    167                 except Exception, msg:
     167                except Exception as msg:
    168168                    pass
    169169
    170170                try:
    171171                    self._srs = gdal.SpatialReference(self.proj4text)
    172172                    return self.srs
    173                 except Exception, msg:
     173                except Exception as msg:
    174174                    pass
    175175
    176176                raise Exception('Could not get OSR SpatialReference from WKT: %s\nError:\n%s' % (self.wkt, msg))
  • django/contrib/gis/db/backends/oracle/introspection.py

    diff --git a/django/contrib/gis/db/backends/oracle/introspection.py b/django/contrib/gis/db/backends/oracle/introspection.py
    index 58dd3f3..716f318 100644
    a b class OracleIntrospection(DatabaseIntrospection):  
    1616                cursor.execute('SELECT "DIMINFO", "SRID" FROM "USER_SDO_GEOM_METADATA" WHERE "TABLE_NAME"=%s AND "COLUMN_NAME"=%s',
    1717                               (table_name.upper(), geo_col.upper()))
    1818                row = cursor.fetchone()
    19             except Exception, msg:
     19            except Exception as msg:
    2020                raise Exception('Could not find entry in USER_SDO_GEOM_METADATA corresponding to "%s"."%s"\n'
    2121                                'Error message: %s.' % (table_name, geo_col, msg))
    2222
  • django/contrib/gis/db/backends/postgis/operations.py

    diff --git a/django/contrib/gis/db/backends/postgis/operations.py b/django/contrib/gis/db/backends/postgis/operations.py
    index 3286748..9dcfe4c 100644
    a b class PostGISOperations(DatabaseOperations, BaseSpatialOperations):  
    107107                                       'Was the database created from a spatial database '
    108108                                       'template?' % self.connection.settings_dict['NAME']
    109109                                       )
    110         except Exception, e:
     110        except Exception as e:
    111111            # TODO: Raise helpful exceptions as they become known.
    112112            raise
    113113
  • django/contrib/gis/db/backends/spatialite/base.py

    diff --git a/django/contrib/gis/db/backends/spatialite/base.py b/django/contrib/gis/db/backends/spatialite/base.py
    index aea52f5..b447d1d 100644
    a b class DatabaseWrapper(SQLiteDatabaseWrapper):  
    5656            cur = self.connection.cursor(factory=SQLiteCursorWrapper)
    5757            try:
    5858                cur.execute("SELECT load_extension(%s)", (self.spatialite_lib,))
    59             except Exception, msg:
     59            except Exception as msg:
    6060                raise ImproperlyConfigured('Unable to load the SpatiaLite library extension '
    6161                                           '"%s" because: %s' % (self.spatialite_lib, msg))
    6262            return cur
  • django/contrib/gis/db/backends/spatialite/operations.py

    diff --git a/django/contrib/gis/db/backends/spatialite/operations.py b/django/contrib/gis/db/backends/spatialite/operations.py
    index a0efb99..6adcdc5 100644
    a b class SpatiaLiteOperations(DatabaseOperations, BaseSpatialOperations):  
    122122            self.spatial_version = version
    123123        except ImproperlyConfigured:
    124124            raise
    125         except Exception, msg:
     125        except Exception as msg:
    126126            raise ImproperlyConfigured('Cannot determine the SpatiaLite version for the "%s" '
    127127                                       'database (error was "%s").  Was the SpatiaLite initialization '
    128128                                       'SQL loaded on this database?' %
  • django/contrib/gis/geometry/backend/__init__.py

    diff --git a/django/contrib/gis/geometry/backend/__init__.py b/django/contrib/gis/geometry/backend/__init__.py
    index d79a556..2e2495d 100644
    a b geom_backend = getattr(settings, 'GEOMETRY_BACKEND', 'geos')  
    66
    77try:
    88    module = import_module('.%s' % geom_backend, 'django.contrib.gis.geometry.backend')
    9 except ImportError, e:
     9except ImportError as e:
    1010    try:
    1111        module = import_module(geom_backend)
    12     except ImportError, e_user:
     12    except ImportError as e_user:
    1313        raise ImproperlyConfigured('Could not import user-defined GEOMETRY_BACKEND '
    1414                                   '"%s".' % geom_backend)
    1515
  • django/contrib/gis/management/commands/ogrinspect.py

    diff --git a/django/contrib/gis/management/commands/ogrinspect.py b/django/contrib/gis/management/commands/ogrinspect.py
    index fbc6f53..6037cc7 100644
    a b class Command(LabelCommand):  
    8787        # Getting the OGR DataSource from the string parameter.
    8888        try:
    8989            ds = gdal.DataSource(data_source)
    90         except gdal.OGRException, msg:
     90        except gdal.OGRException as msg:
    9191            raise CommandError(msg)
    9292
    9393        # Whether the user wants to generate the LayerMapping dictionary as well.
  • django/contrib/gis/tests/test_measure.py

    diff --git a/django/contrib/gis/tests/test_measure.py b/django/contrib/gis/tests/test_measure.py
    index 8ca6be1..6792569 100644
    a b class DistanceTest(unittest.TestCase):  
    6464
    6565        try:
    6666            d5 = d1 + 1
    67         except TypeError, e:
     67        except TypeError as e:
    6868            pass
    6969        else:
    7070            self.fail('Distance + number should raise TypeError')
    7171
    7272        try:
    7373            d5 = d1 - 1
    74         except TypeError, e:
     74        except TypeError as e:
    7575            pass
    7676        else:
    7777            self.fail('Distance - number should raise TypeError')
    7878
    7979        try:
    8080            d1 += 1
    81         except TypeError, e:
     81        except TypeError as e:
    8282            pass
    8383        else:
    8484            self.fail('Distance += number should raise TypeError')
    8585
    8686        try:
    8787            d1 -= 1
    88         except TypeError, e:
     88        except TypeError as e:
    8989            pass
    9090        else:
    9191            self.fail('Distance -= number should raise TypeError')
    class DistanceTest(unittest.TestCase):  
    112112
    113113        try:
    114114            d1 *= D(m=1)
    115         except TypeError, e:
     115        except TypeError as e:
    116116            pass
    117117        else:
    118118            self.fail('Distance *= Distance should raise TypeError')
    119119
    120120        try:
    121121            d5 = d1 / D(m=1)
    122         except TypeError, e:
     122        except TypeError as e:
    123123            pass
    124124        else:
    125125            self.fail('Distance / Distance should raise TypeError')
    126126
    127127        try:
    128128            d1 /= D(m=1)
    129         except TypeError, e:
     129        except TypeError as e:
    130130            pass
    131131        else:
    132132            self.fail('Distance /= Distance should raise TypeError')
    class AreaTest(unittest.TestCase):  
    219219
    220220        try:
    221221            a5 = a1 + 1
    222         except TypeError, e:
     222        except TypeError as e:
    223223            pass
    224224        else:
    225225            self.fail('Area + number should raise TypeError')
    226226
    227227        try:
    228228            a5 = a1 - 1
    229         except TypeError, e:
     229        except TypeError as e:
    230230            pass
    231231        else:
    232232            self.fail('Area - number should raise TypeError')
    233233
    234234        try:
    235235            a1 += 1
    236         except TypeError, e:
     236        except TypeError as e:
    237237            pass
    238238        else:
    239239            self.fail('Area += number should raise TypeError')
    240240
    241241        try:
    242242            a1 -= 1
    243         except TypeError, e:
     243        except TypeError as e:
    244244            pass
    245245        else:
    246246            self.fail('Area -= number should raise TypeError')
    class AreaTest(unittest.TestCase):  
    263263
    264264        try:
    265265            a5 = a1 * A(sq_m=1)
    266         except TypeError, e:
     266        except TypeError as e:
    267267            pass
    268268        else:
    269269            self.fail('Area * Area should raise TypeError')
    270270
    271271        try:
    272272            a1 *= A(sq_m=1)
    273         except TypeError, e:
     273        except TypeError as e:
    274274            pass
    275275        else:
    276276            self.fail('Area *= Area should raise TypeError')
    277277
    278278        try:
    279279            a5 = a1 / A(sq_m=1)
    280         except TypeError, e:
     280        except TypeError as e:
    281281            pass
    282282        else:
    283283            self.fail('Area / Area should raise TypeError')
    284284
    285285        try:
    286286            a1 /= A(sq_m=1)
    287         except TypeError, e:
     287        except TypeError as e:
    288288            pass
    289289        else:
    290290            self.fail('Area /= Area should raise TypeError')
  • django/contrib/gis/utils/layermapping.py

    diff --git a/django/contrib/gis/utils/layermapping.py b/django/contrib/gis/utils/layermapping.py
    index 154617f..ea3f3d7 100644
    a b class LayerMapping(object):  
    430430
    431431            # Creating the CoordTransform object
    432432            return CoordTransform(self.source_srs, target_srs)
    433         except Exception, msg:
     433        except Exception as msg:
    434434            raise LayerMapError('Could not translate between the data source and model geometry: %s' % msg)
    435435
    436436    def geometry_field(self):
    class LayerMapping(object):  
    514514                # Getting the keyword arguments
    515515                try:
    516516                    kwargs = self.feature_kwargs(feat)
    517                 except LayerMapError, msg:
     517                except LayerMapError as msg:
    518518                    # Something borked the validation
    519519                    if strict: raise
    520520                    elif not silent:
    class LayerMapping(object):  
    553553                        if verbose: stream.write('%s: %s\n' % (is_update and 'Updated' or 'Saved', m))
    554554                    except SystemExit:
    555555                        raise
    556                     except Exception, msg:
     556                    except Exception as msg:
    557557                        if self.transaction_mode == 'autocommit':
    558558                            # Rolling back the transaction so that other model saves
    559559                            # will work.
  • django/contrib/markup/tests.py

    diff --git a/django/contrib/markup/tests.py b/django/contrib/markup/tests.py
    index cccb5c8..05df318 100644
    a b Paragraph 2 with a link_  
    8787            # Docutils v0.4 and earlier
    8888            self.assertEqual(rendered, """<p>Paragraph 1</p>
    8989<p>Paragraph 2 with a <a class="reference" href="http://www.example.com/">link</a></p>""")
    90         except AssertionError, e:
     90        except AssertionError as e:
    9191            # Docutils from SVN (which will become 0.5)
    9292            self.assertEqual(rendered, """<p>Paragraph 1</p>
    9393<p>Paragraph 2 with a <a class="reference external" href="http://www.example.com/">link</a></p>""")
  • django/contrib/messages/storage/__init__.py

    diff --git a/django/contrib/messages/storage/__init__.py b/django/contrib/messages/storage/__init__.py
    index ce3971b..a584acc 100644
    a b def get_storage(import_path):  
    1515    module, classname = import_path[:dot], import_path[dot + 1:]
    1616    try:
    1717        mod = import_module(module)
    18     except ImportError, e:
     18    except ImportError as e:
    1919        raise ImproperlyConfigured('Error importing module %s: "%s"' %
    2020                                   (module, e))
    2121    try:
  • django/contrib/sessions/backends/file.py

    diff --git a/django/contrib/sessions/backends/file.py b/django/contrib/sessions/backends/file.py
    index 8ffddc4..cb81534 100644
    a b class SessionStore(SessionBase):  
    9090            fd = os.open(session_file_name, flags)
    9191            os.close(fd)
    9292
    93         except OSError, e:
     93        except OSError as e:
    9494            if must_create and e.errno == errno.EEXIST:
    9595                raise CreateError
    9696            raise
  • django/contrib/staticfiles/finders.py

    diff --git a/django/contrib/staticfiles/finders.py b/django/contrib/staticfiles/finders.py
    index 7b4c7c8..766687c 100644
    a b def _get_finder(import_path):  
    260260    module, attr = import_path.rsplit('.', 1)
    261261    try:
    262262        mod = import_module(module)
    263     except ImportError, e:
     263    except ImportError as e:
    264264        raise ImproperlyConfigured('Error importing module %s: "%s"' %
    265265                                   (module, e))
    266266    try:
  • django/contrib/staticfiles/handlers.py

    diff --git a/django/contrib/staticfiles/handlers.py b/django/contrib/staticfiles/handlers.py
    index 962b835..f475b22 100644
    a b class StaticFilesHandler(WSGIHandler):  
    5656        if self._should_handle(request.path):
    5757            try:
    5858                return self.serve(request)
    59             except Http404, e:
     59            except Http404 as e:
    6060                if settings.DEBUG:
    6161                    from django.views import debug
    6262                    return debug.technical_404_response(request, e)
  • django/core/cache/__init__.py

    diff --git a/django/core/cache/__init__.py b/django/core/cache/__init__.py
    index 346deae..3b40555 100644
    a b def get_cache(backend, **kwargs):  
    173173            mod_path, cls_name = backend.rsplit('.', 1)
    174174            mod = importlib.import_module(mod_path)
    175175            backend_cls = getattr(mod, cls_name)
    176     except (AttributeError, ImportError), e:
     176    except (AttributeError, ImportError) as e:
    177177        raise InvalidCacheBackendError(
    178178            "Could not find backend '%s': %s" % (backend, e))
    179179    cache = backend_cls(location, params)
  • django/core/files/move.py

    diff --git a/django/core/files/move.py b/django/core/files/move.py
    index 3349fc2..4778228 100644
    a b def file_move_safe(old_file_name, new_file_name, chunk_size = 1024*64, allow_ove  
    7979
    8080    try:
    8181        os.remove(old_file_name)
    82     except OSError, e:
     82    except OSError as e:
    8383        # Certain operating systems (Cygwin and Windows)
    8484        # fail when deleting opened files, ignore it.  (For the
    8585        # systems where this happens, temporary files will be auto-deleted
  • django/core/files/storage.py

    diff --git a/django/core/files/storage.py b/django/core/files/storage.py
    index aa62175..6b724b4 100644
    a b class FileSystemStorage(Storage):  
    166166        if not os.path.exists(directory):
    167167            try:
    168168                os.makedirs(directory)
    169             except OSError, e:
     169            except OSError as e:
    170170                if e.errno != errno.EEXIST:
    171171                    raise
    172172        if not os.path.isdir(directory):
    class FileSystemStorage(Storage):  
    197197                    finally:
    198198                        locks.unlock(fd)
    199199                        os.close(fd)
    200             except OSError, e:
     200            except OSError as e:
    201201                if e.errno == errno.EEXIST:
    202202                    # Ooops, the file exists. We need a new file name.
    203203                    name = self.get_available_name(name)
    class FileSystemStorage(Storage):  
    222222        if os.path.exists(name):
    223223            try:
    224224                os.remove(name)
    225             except OSError, e:
     225            except OSError as e:
    226226                if e.errno != errno.ENOENT:
    227227                    raise
    228228
    def get_storage_class(import_path=None):  
    273273    module, classname = import_path[:dot], import_path[dot+1:]
    274274    try:
    275275        mod = import_module(module)
    276     except ImportError, e:
     276    except ImportError as e:
    277277        raise ImproperlyConfigured('Error importing storage module %s: "%s"' % (module, e))
    278278    try:
    279279        return getattr(mod, classname)
  • django/core/files/uploadedfile.py

    diff --git a/django/core/files/uploadedfile.py b/django/core/files/uploadedfile.py
    index 5178f0b..1dcd9ae 100644
    a b class TemporaryUploadedFile(UploadedFile):  
    7575    def close(self):
    7676        try:
    7777            return self.file.close()
    78         except OSError, e:
     78        except OSError as e:
    7979            if e.errno != 2:
    8080                # Means the file was moved or deleted before the tempfile
    8181                # could unlink it.  Still sets self.file.close_called and
  • django/core/files/uploadhandler.py

    diff --git a/django/core/files/uploadhandler.py b/django/core/files/uploadhandler.py
    index 2afb79e..b806098 100644
    a b def load_handler(path, *args, **kwargs):  
    204204    module, attr = path[:i], path[i+1:]
    205205    try:
    206206        mod = importlib.import_module(module)
    207     except ImportError, e:
     207    except ImportError as e:
    208208        raise ImproperlyConfigured('Error importing upload handler module %s: "%s"' % (module, e))
    209     except ValueError, e:
     209    except ValueError as e:
    210210        raise ImproperlyConfigured('Error importing upload handler module. Is FILE_UPLOAD_HANDLERS a correctly defined list or tuple?')
    211211    try:
    212212        cls = getattr(mod, attr)
  • django/core/handlers/base.py

    diff --git a/django/core/handlers/base.py b/django/core/handlers/base.py
    index a0918bf..4c9dfc0 100644
    a b class BaseHandler(object):  
    4343                raise exceptions.ImproperlyConfigured('%s isn\'t a middleware module' % middleware_path)
    4444            try:
    4545                mod = import_module(mw_module)
    46             except ImportError, e:
     46            except ImportError as e:
    4747                raise exceptions.ImproperlyConfigured('Error importing middleware %s: "%s"' % (mw_module, e))
    4848            try:
    4949                mw_class = getattr(mod, mw_classname)
    class BaseHandler(object):  
    109109                if response is None:
    110110                    try:
    111111                        response = callback(request, *callback_args, **callback_kwargs)
    112                     except Exception, e:
     112                    except Exception as e:
    113113                        # If the view raised an exception, run it through exception
    114114                        # middleware, and if the exception middleware returns a
    115115                        # response, use that. Otherwise, reraise the exception.
    class BaseHandler(object):  
    135135                        response = middleware_method(request, response)
    136136                    response = response.render()
    137137
    138             except http.Http404, e:
     138            except http.Http404 as e:
    139139                logger.warning('Not Found: %s', request.path,
    140140                            extra={
    141141                                'status_code': 404,
  • django/core/mail/__init__.py

    diff --git a/django/core/mail/__init__.py b/django/core/mail/__init__.py
    index 7ab02c3..3e3ef0d 100644
    a b def get_connection(backend=None, fail_silently=False, **kwds):  
    3030    try:
    3131        mod_name, klass_name = path.rsplit('.', 1)
    3232        mod = import_module(mod_name)
    33     except ImportError, e:
     33    except ImportError as e:
    3434        raise ImproperlyConfigured(('Error importing email backend module %s: "%s"'
    3535                                    % (mod_name, e)))
    3636    try:
  • django/core/mail/backends/filebased.py

    diff --git a/django/core/mail/backends/filebased.py b/django/core/mail/backends/filebased.py
    index 3f6b99b..674ca32 100644
    a b class EmailBackend(ConsoleEmailBackend):  
    2525        elif not os.path.exists(self.file_path):
    2626            try:
    2727                os.makedirs(self.file_path)
    28             except OSError, err:
     28            except OSError as err:
    2929                raise ImproperlyConfigured('Could not create directory for saving email messages: %s (%s)' % (self.file_path, err))
    3030        # Make sure that self.file_path is writable.
    3131        if not os.access(self.file_path, os.W_OK):
  • django/core/management/base.py

    diff --git a/django/core/management/base.py b/django/core/management/base.py
    index db855e1..42c9ccd 100644
    a b class BaseCommand(object):  
    215215                from django.utils import translation
    216216                saved_lang = translation.get_language()
    217217                translation.activate('en-us')
    218             except ImportError, e:
     218            except ImportError as e:
    219219                # If settings should be available, but aren't,
    220220                # raise the error and quit.
    221221                if show_traceback:
    class BaseCommand(object):  
    241241                self.stdout.write(output)
    242242                if self.output_transaction:
    243243                    self.stdout.write('\n' + self.style.SQL_KEYWORD("COMMIT;") + '\n')
    244         except CommandError, e:
     244        except CommandError as e:
    245245            if show_traceback:
    246246                traceback.print_exc()
    247247            else:
    class AppCommand(BaseCommand):  
    297297            raise CommandError('Enter at least one appname.')
    298298        try:
    299299            app_list = [models.get_app(app_label) for app_label in app_labels]
    300         except (ImproperlyConfigured, ImportError), e:
     300        except (ImproperlyConfigured, ImportError) as e:
    301301            raise CommandError("%s. Are you sure your INSTALLED_APPS setting is correct?" % e)
    302302        output = []
    303303        for app in app_list:
  • django/core/management/commands/createcachetable.py

    diff --git a/django/core/management/commands/createcachetable.py b/django/core/management/commands/createcachetable.py
    index 7164d1a..82a126b 100644
    a b class Command(LabelCommand):  
    5454        curs = connection.cursor()
    5555        try:
    5656            curs.execute("\n".join(full_statement))
    57         except DatabaseError, e:
     57        except DatabaseError as e:
    5858            self.stderr.write(
    5959                self.style.ERROR("Cache table '%s' could not be created.\nThe error was: %s.\n" %
    6060                    (tablename, e)))
  • django/core/management/commands/dumpdata.py

    diff --git a/django/core/management/commands/dumpdata.py b/django/core/management/commands/dumpdata.py
    index 1622929..71d6fa7 100644
    a b class Command(BaseCommand):  
    111111        try:
    112112            return serializers.serialize(format, objects, indent=indent,
    113113                        use_natural_keys=use_natural_keys)
    114         except Exception, e:
     114        except Exception as e:
    115115            if show_traceback:
    116116                raise
    117117            raise CommandError("Unable to serialize database: %s" % e)
  • django/core/management/commands/flush.py

    diff --git a/django/core/management/commands/flush.py b/django/core/management/commands/flush.py
    index 6d0f14e..12a276e 100644
    a b Are you sure you want to do this?  
    5555                cursor = connection.cursor()
    5656                for sql in sql_list:
    5757                    cursor.execute(sql)
    58             except Exception, e:
     58            except Exception as e:
    5959                transaction.rollback_unless_managed(using=db)
    6060                raise CommandError("""Database %s couldn't be flushed. Possible reasons:
    6161  * The database isn't running or isn't configured correctly.
  • django/core/management/commands/loaddata.py

    diff --git a/django/core/management/commands/loaddata.py b/django/core/management/commands/loaddata.py
    index 0c234fb..d066343 100644
    a b class Command(BaseCommand):  
    194194                                            models.add(obj.object.__class__)
    195195                                            try:
    196196                                                obj.save(using=using)
    197                                             except (DatabaseError, IntegrityError), e:
     197                                            except (DatabaseError, IntegrityError) as e:
    198198                                                msg = "Could not load %(app_label)s.%(object_name)s(pk=%(pk)s): %(error_msg)s" % {
    199199                                                        'app_label': obj.object._meta.app_label,
    200200                                                        'object_name': obj.object._meta.object_name,
  • django/core/management/commands/reset.py

    diff --git a/django/core/management/commands/reset.py b/django/core/management/commands/reset.py
    index e45edb7..4ac1a03 100644
    a b Type 'yes' to continue, or 'no' to cancel: """ % (app_name, connection.settings_  
    4949                cursor = connection.cursor()
    5050                for sql in sql_list:
    5151                    cursor.execute(sql)
    52             except Exception, e:
     52            except Exception as e:
    5353                transaction.rollback_unless_managed()
    5454                raise CommandError("""Error: %s couldn't be reset. Possible reasons:
    5555  * The database isn't running or isn't configured correctly.
  • django/core/management/commands/runserver.py

    diff --git a/django/core/management/commands/runserver.py b/django/core/management/commands/runserver.py
    index e93af96..3ec4ea8 100644
    a b class BaseRunserverCommand(BaseCommand):  
    109109            handler = self.get_handler(*args, **options)
    110110            run(self.addr, int(self.port), handler,
    111111                ipv6=self.use_ipv6, threading=threading)
    112         except WSGIServerException, e:
     112        except WSGIServerException as e:
    113113            # Use helpful error messages instead of ugly tracebacks.
    114114            ERRORS = {
    115115                13: "You don't have permission to access that port.",
  • django/core/management/commands/syncdb.py

    diff --git a/django/core/management/commands/syncdb.py b/django/core/management/commands/syncdb.py
    index 852fa15..1f5d2ed 100644
    a b class Command(NoArgsCommand):  
    3838        for app_name in settings.INSTALLED_APPS:
    3939            try:
    4040                import_module('.management', app_name)
    41             except ImportError, exc:
     41            except ImportError as exc:
    4242                # This is slightly hackish. We want to ignore ImportErrors
    4343                # if the "management" module itself is missing -- but we don't
    4444                # want to ignore the exception if the management module exists
    class Command(NoArgsCommand):  
    126126                        try:
    127127                            for sql in custom_sql:
    128128                                cursor.execute(sql)
    129                         except Exception, e:
     129                        except Exception as e:
    130130                            sys.stderr.write("Failed to install custom SQL for %s.%s model: %s\n" % \
    131131                                                (app_name, model._meta.object_name, e))
    132132                            if show_traceback:
    class Command(NoArgsCommand):  
    151151                        try:
    152152                            for sql in index_sql:
    153153                                cursor.execute(sql)
    154                         except Exception, e:
     154                        except Exception as e:
    155155                            sys.stderr.write("Failed to install index for %s.%s model: %s\n" % \
    156156                                                (app_name, model._meta.object_name, e))
    157157                            transaction.rollback_unless_managed(using=db)
  • django/core/management/templates.py

    diff --git a/django/core/management/templates.py b/django/core/management/templates.py
    index 9a4b2c1..6bf1888 100644
    a b class TemplateCommand(BaseCommand):  
    8282            top_dir = path.join(os.getcwd(), name)
    8383            try:
    8484                os.makedirs(top_dir)
    85             except OSError, e:
     85            except OSError as e:
    8686                if e.errno == errno.EEXIST:
    8787                    message = "'%s' already exists" % top_dir
    8888                else:
    class TemplateCommand(BaseCommand):  
    232232        try:
    233233            the_path, info = urllib.urlretrieve(url,
    234234                                                path.join(tempdir, filename))
    235         except IOError, e:
     235        except IOError as e:
    236236            raise CommandError("couldn't download URL %s to %s: %s" %
    237237                               (url, filename, e))
    238238
    class TemplateCommand(BaseCommand):  
    287287        try:
    288288            archive.extract(filename, tempdir)
    289289            return tempdir
    290         except (archive.ArchiveException, IOError), e:
     290        except (archive.ArchiveException, IOError) as e:
    291291            raise CommandError("couldn't extract file %s to %s: %s" %
    292292                               (filename, tempdir, e))
    293293
  • django/core/serializers/json.py

    diff --git a/django/core/serializers/json.py b/django/core/serializers/json.py
    index 91af84e..e9570b8 100644
    a b def Deserializer(stream_or_string, **options):  
    4242            yield obj
    4343    except GeneratorExit:
    4444        raise
    45     except Exception, e:
     45    except Exception as e:
    4646        # Map to deserializer error
    4747        raise DeserializationError(e)
    4848
  • django/core/serializers/pyyaml.py

    diff --git a/django/core/serializers/pyyaml.py b/django/core/serializers/pyyaml.py
    index 7a508da..dc884a6 100644
    a b def Deserializer(stream_or_string, **options):  
    5757            yield obj
    5858    except GeneratorExit:
    5959        raise
    60     except Exception, e:
     60    except Exception as e:
    6161        # Map to deserializer error
    6262        raise DeserializationError(e)
  • django/core/servers/basehttp.py

    diff --git a/django/core/servers/basehttp.py b/django/core/servers/basehttp.py
    index 8d4ceab..f728ea1 100644
    a b def get_internal_wsgi_application():  
    5252    module_name, attr = app_path.rsplit('.', 1)
    5353    try:
    5454        mod = import_module(module_name)
    55     except ImportError, e:
     55    except ImportError as e:
    5656        raise ImproperlyConfigured(
    5757            "WSGI application '%s' could not be loaded; "
    5858            "could not import module '%s': %s" % (app_path, module_name, e))
    5959    try:
    6060        app = getattr(mod, attr)
    61     except AttributeError, e:
     61    except AttributeError as e:
    6262        raise ImproperlyConfigured(
    6363            "WSGI application '%s' could not be loaded; "
    6464            "can't find '%s' in module '%s': %s"
    class WSGIServer(simple_server.WSGIServer, object):  
    122122        """Override server_bind to store the server name."""
    123123        try:
    124124            super(WSGIServer, self).server_bind()
    125         except Exception, e:
     125        except Exception as e:
    126126            raise WSGIServerException(e)
    127127        self.setup_environ()
    128128
  • django/core/servers/fastcgi.py

    diff --git a/django/core/servers/fastcgi.py b/django/core/servers/fastcgi.py
    index 17fd609..9c652a7 100644
    a b def runfastcgi(argset=[], **kwargs):  
    102102
    103103    try:
    104104        import flup
    105     except ImportError, e:
     105    except ImportError as e:
    106106        print >> sys.stderr, "ERROR: %s" % e
    107107        print >> sys.stderr, "  Unable to load the flup package.  In order to run django"
    108108        print >> sys.stderr, "  as a FastCGI application, you will need to get flup from"
  • django/core/signing.py

    diff --git a/django/core/signing.py b/django/core/signing.py
    index 7f92d61..78a8659 100644
    a b def get_cookie_signer(salt='django.core.signing.get_cookie_signer'):  
    7676    module, attr = modpath.rsplit('.', 1)
    7777    try:
    7878        mod = import_module(module)
    79     except ImportError, e:
     79    except ImportError as e:
    8080        raise ImproperlyConfigured(
    8181            'Error importing cookie signer %s: "%s"' % (modpath, e))
    8282    try:
    8383        Signer = getattr(mod, attr)
    84     except AttributeError, e:
     84    except AttributeError as e:
    8585        raise ImproperlyConfigured(
    8686            'Error importing cookie signer %s: "%s"' % (modpath, e))
    8787    return Signer('django.http.cookies' + settings.SECRET_KEY, salt=salt)
  • django/core/urlresolvers.py

    diff --git a/django/core/urlresolvers.py b/django/core/urlresolvers.py
    index 1497d43..aadd290 100644
    a b class RegexURLResolver(LocaleRegexProvider):  
    298298            for pattern in self.url_patterns:
    299299                try:
    300300                    sub_match = pattern.resolve(new_path)
    301                 except Resolver404, e:
     301                except Resolver404 as e:
    302302                    sub_tried = e.args[0].get('tried')
    303303                    if sub_tried is not None:
    304304                        tried.extend([[pattern] + t for t in sub_tried])
    class RegexURLResolver(LocaleRegexProvider):  
    358358            raise ValueError("Don't mix *args and **kwargs in call to reverse()!")
    359359        try:
    360360            lookup_view = get_callable(lookup_view, True)
    361         except (ImportError, AttributeError), e:
     361        except (ImportError, AttributeError) as e:
    362362            raise NoReverseMatch("Error importing '%s': %s." % (lookup_view, e))
    363363        possibilities = self.reverse_dict.getlist(lookup_view)
    364364        prefix_norm, prefix_args = normalize(_prefix)[0]
    def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None, current  
    462462                extra, resolver = resolver.namespace_dict[ns]
    463463                resolved_path.append(ns)
    464464                ns_pattern = ns_pattern + extra
    465             except KeyError, key:
     465            except KeyError as key:
    466466                if resolved_path:
    467467                    raise NoReverseMatch(
    468468                        "%s is not a registered namespace inside '%s'" %
  • django/core/validators.py

    diff --git a/django/core/validators.py b/django/core/validators.py
    index 95224e9..52971e2 100644
    a b class URLValidator(RegexValidator):  
    6161    def __call__(self, value):
    6262        try:
    6363            super(URLValidator, self).__call__(value)
    64         except ValidationError, e:
     64        except ValidationError as e:
    6565            # Trivial case failed. Try for possible IDN domain
    6666            if value:
    6767                value = smart_unicode(value)
    class EmailValidator(RegexValidator):  
    144144    def __call__(self, value):
    145145        try:
    146146            super(EmailValidator, self).__call__(value)
    147         except ValidationError, e:
     147        except ValidationError as e:
    148148            # Trivial case failed. Try for possible IDN domain-part
    149149            if value and u'@' in value:
    150150                parts = value.split(u'@')
  • django/db/backends/creation.py

    diff --git a/django/db/backends/creation.py b/django/db/backends/creation.py
    index 0cd0558..2e3b7e5 100644
    a b class BaseDatabaseCreation(object):  
    323323        try:
    324324            cursor.execute(
    325325                "CREATE DATABASE %s %s" % (qn(test_database_name), suffix))
    326         except Exception, e:
     326        except Exception as e:
    327327            sys.stderr.write(
    328328                "Got an error creating the test database: %s\n" % e)
    329329            if not autoclobber:
    class BaseDatabaseCreation(object):  
    340340                    cursor.execute(
    341341                        "CREATE DATABASE %s %s" % (qn(test_database_name),
    342342                                                   suffix))
    343                 except Exception, e:
     343                except Exception as e:
    344344                    sys.stderr.write(
    345345                        "Got an error recreating the test database: %s\n" % e)
    346346                    sys.exit(2)
  • django/db/backends/mysql/base.py

    diff --git a/django/db/backends/mysql/base.py b/django/db/backends/mysql/base.py
    index faaefca..c272f9f 100644
    a b import warnings  
    1111
    1212try:
    1313    import MySQLdb as Database
    14 except ImportError, e:
     14except ImportError as e:
    1515    from django.core.exceptions import ImproperlyConfigured
    1616    raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
    1717
    class CursorWrapper(object):  
    112112    def execute(self, query, args=None):
    113113        try:
    114114            return self.cursor.execute(query, args)
    115         except Database.IntegrityError, e:
     115        except Database.IntegrityError as e:
    116116            raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
    117         except Database.OperationalError, e:
     117        except Database.OperationalError as e:
    118118            # Map some error codes to IntegrityError, since they seem to be
    119119            # misclassified and Django would prefer the more logical place.
    120120            if e[0] in self.codes_for_integrityerror:
    121121                raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
    122122            raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
    123         except Database.DatabaseError, e:
     123        except Database.DatabaseError as e:
    124124            raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
    125125
    126126    def executemany(self, query, args):
    127127        try:
    128128            return self.cursor.executemany(query, args)
    129         except Database.IntegrityError, e:
     129        except Database.IntegrityError as e:
    130130            raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
    131         except Database.OperationalError, e:
     131        except Database.OperationalError as e:
    132132            # Map some error codes to IntegrityError, since they seem to be
    133133            # misclassified and Django would prefer the more logical place.
    134134            if e[0] in self.codes_for_integrityerror:
    135135                raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
    136136            raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
    137         except Database.DatabaseError, e:
     137        except Database.DatabaseError as e:
    138138            raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
    139139
    140140    def __getattr__(self, attr):
  • django/db/backends/oracle/base.py

    diff --git a/django/db/backends/oracle/base.py b/django/db/backends/oracle/base.py
    index fc02ac4..9c91baa 100644
    a b def _setup_environment(environ):  
    1818    if platform.system().upper().startswith('CYGWIN'):
    1919        try:
    2020            import ctypes
    21         except ImportError, e:
     21        except ImportError as e:
    2222            from django.core.exceptions import ImproperlyConfigured
    2323            raise ImproperlyConfigured("Error loading ctypes: %s; "
    2424                                       "the Oracle backend requires ctypes to "
    _setup_environment([  
    4141
    4242try:
    4343    import cx_Oracle as Database
    44 except ImportError, e:
     44except ImportError as e:
    4545    from django.core.exceptions import ImproperlyConfigured
    4646    raise ImproperlyConfigured("Error loading cx_Oracle module: %s" % e)
    4747
    class DatabaseWrapper(BaseDatabaseWrapper):  
    532532        if self.connection is not None:
    533533            try:
    534534                return self.connection.commit()
    535             except Database.IntegrityError, e:
     535            except Database.IntegrityError as e:
    536536                # In case cx_Oracle implements (now or in a future version)
    537537                # raising this specific exception
    538538                raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
    539             except Database.DatabaseError, e:
     539            except Database.DatabaseError as e:
    540540                # cx_Oracle 5.0.4 raises a cx_Oracle.DatabaseError exception
    541541                # with the following attributes and values:
    542542                #  code = 2091
    class FormatStylePlaceholderCursor(object):  
    673673        self._guess_input_sizes([params])
    674674        try:
    675675            return self.cursor.execute(query, self._param_generator(params))
    676         except Database.IntegrityError, e:
     676        except Database.IntegrityError as e:
    677677            raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
    678         except Database.DatabaseError, e:
     678        except Database.DatabaseError as e:
    679679            # cx_Oracle <= 4.4.0 wrongly raises a DatabaseError for ORA-01400.
    680680            if hasattr(e.args[0], 'code') and e.args[0].code == 1400 and not isinstance(e, IntegrityError):
    681681                raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
    class FormatStylePlaceholderCursor(object):  
    702702        try:
    703703            return self.cursor.executemany(query,
    704704                                [self._param_generator(p) for p in formatted])
    705         except Database.IntegrityError, e:
     705        except Database.IntegrityError as e:
    706706            raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
    707         except Database.DatabaseError, e:
     707        except Database.DatabaseError as e:
    708708            # cx_Oracle <= 4.4.0 wrongly raises a DatabaseError for ORA-01400.
    709709            if hasattr(e.args[0], 'code') and e.args[0].code == 1400 and not isinstance(e, IntegrityError):
    710710                raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
  • django/db/backends/oracle/creation.py

    diff --git a/django/db/backends/oracle/creation.py b/django/db/backends/oracle/creation.py
    index 9e6133f..758c9ec 100644
    a b class DatabaseCreation(BaseDatabaseCreation):  
    6262        if self._test_database_create():
    6363            try:
    6464                self._execute_test_db_creation(cursor, parameters, verbosity)
    65             except Exception, e:
     65            except Exception as e:
    6666                sys.stderr.write("Got an error creating the test database: %s\n" % e)
    6767                if not autoclobber:
    6868                    confirm = raw_input("It appears the test database, %s, already exists. Type 'yes' to delete it, or 'no' to cancel: " % TEST_NAME)
    class DatabaseCreation(BaseDatabaseCreation):  
    7272                            print "Destroying old test database '%s'..." % self.connection.alias
    7373                        self._execute_test_db_destruction(cursor, parameters, verbosity)
    7474                        self._execute_test_db_creation(cursor, parameters, verbosity)
    75                     except Exception, e:
     75                    except Exception as e:
    7676                        sys.stderr.write("Got an error recreating the test database: %s\n" % e)
    7777                        sys.exit(2)
    7878                else:
    class DatabaseCreation(BaseDatabaseCreation):  
    8484                print "Creating test user..."
    8585            try:
    8686                self._create_test_user(cursor, parameters, verbosity)
    87             except Exception, e:
     87            except Exception as e:
    8888                sys.stderr.write("Got an error creating the test user: %s\n" % e)
    8989                if not autoclobber:
    9090                    confirm = raw_input("It appears the test user, %s, already exists. Type 'yes' to delete it, or 'no' to cancel: " % TEST_USER)
    class DatabaseCreation(BaseDatabaseCreation):  
    9696                        if verbosity >= 1:
    9797                            print "Creating test user..."
    9898                        self._create_test_user(cursor, parameters, verbosity)
    99                     except Exception, e:
     99                    except Exception as e:
    100100                        sys.stderr.write("Got an error recreating the test user: %s\n" % e)
    101101                        sys.exit(2)
    102102                else:
    class DatabaseCreation(BaseDatabaseCreation):  
    197197                print stmt
    198198            try:
    199199                cursor.execute(stmt)
    200             except Exception, err:
     200            except Exception as err:
    201201                sys.stderr.write("Failed (%s)\n" % (err))
    202202                raise
    203203
  • django/db/backends/postgresql_psycopg2/base.py

    diff --git a/django/db/backends/postgresql_psycopg2/base.py b/django/db/backends/postgresql_psycopg2/base.py
    index 0d25129..61be680 100644
    a b from django.utils.timezone import utc  
    2020try:
    2121    import psycopg2 as Database
    2222    import psycopg2.extensions
    23 except ImportError, e:
     23except ImportError as e:
    2424    from django.core.exceptions import ImproperlyConfigured
    2525    raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e)
    2626
    class CursorWrapper(object):  
    5050    def execute(self, query, args=None):
    5151        try:
    5252            return self.cursor.execute(query, args)
    53         except Database.IntegrityError, e:
     53        except Database.IntegrityError as e:
    5454            raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
    55         except Database.DatabaseError, e:
     55        except Database.DatabaseError as e:
    5656            raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
    5757
    5858    def executemany(self, query, args):
    5959        try:
    6060            return self.cursor.executemany(query, args)
    61         except Database.IntegrityError, e:
     61        except Database.IntegrityError as e:
    6262            raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
    63         except Database.DatabaseError, e:
     63        except Database.DatabaseError as e:
    6464            raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
    6565
    6666    def __getattr__(self, attr):
    class DatabaseWrapper(BaseDatabaseWrapper):  
    233233        if self.connection is not None:
    234234            try:
    235235                return self.connection.commit()
    236             except Database.IntegrityError, e:
     236            except Database.IntegrityError as e:
    237237                raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
  • django/db/backends/sqlite3/base.py

    diff --git a/django/db/backends/sqlite3/base.py b/django/db/backends/sqlite3/base.py
    index 0b19442..3d389ed 100644
    a b from django.utils import timezone  
    2424try:
    2525    try:
    2626        from pysqlite2 import dbapi2 as Database
    27     except ImportError, e1:
     27    except ImportError as e1:
    2828        from sqlite3 import dbapi2 as Database
    29 except ImportError, exc:
     29except ImportError as exc:
    3030    from django.core.exceptions import ImproperlyConfigured
    3131    raise ImproperlyConfigured("Error loading either pysqlite2 or sqlite3 modules (tried in that order): %s" % exc)
    3232
    class SQLiteCursorWrapper(Database.Cursor):  
    335335        query = self.convert_query(query)
    336336        try:
    337337            return Database.Cursor.execute(self, query, params)
    338         except Database.IntegrityError, e:
     338        except Database.IntegrityError as e:
    339339            raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
    340         except Database.DatabaseError, e:
     340        except Database.DatabaseError as e:
    341341            raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
    342342
    343343    def executemany(self, query, param_list):
    344344        query = self.convert_query(query)
    345345        try:
    346346            return Database.Cursor.executemany(self, query, param_list)
    347         except Database.IntegrityError, e:
     347        except Database.IntegrityError as e:
    348348            raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
    349         except Database.DatabaseError, e:
     349        except Database.DatabaseError as e:
    350350            raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
    351351
    352352    def convert_query(self, query):
  • django/db/backends/sqlite3/creation.py

    diff --git a/django/db/backends/sqlite3/creation.py b/django/db/backends/sqlite3/creation.py
    index 5f55e39..9e660fa 100644
    a b class DatabaseCreation(BaseDatabaseCreation):  
    5757                if autoclobber or confirm == 'yes':
    5858                  try:
    5959                      os.remove(test_database_name)
    60                   except Exception, e:
     60                  except Exception as e:
    6161                      sys.stderr.write("Got an error deleting the old test database: %s\n" % e)
    6262                      sys.exit(2)
    6363                else:
  • django/db/models/base.py

    diff --git a/django/db/models/base.py b/django/db/models/base.py
    index fc38224..b92058c 100644
    a b class Model(object):  
    801801
    802802        try:
    803803            self.clean_fields(exclude=exclude)
    804         except ValidationError, e:
     804        except ValidationError as e:
    805805            errors = e.update_error_dict(errors)
    806806
    807807        # Form.clean() is run even if other validation fails, so do the
    808808        # same with Model.clean() for consistency.
    809809        try:
    810810            self.clean()
    811         except ValidationError, e:
     811        except ValidationError as e:
    812812            errors = e.update_error_dict(errors)
    813813
    814814        # Run unique checks, but only for fields that passed validation.
    class Model(object):  
    817817                exclude.append(name)
    818818        try:
    819819            self.validate_unique(exclude=exclude)
    820         except ValidationError, e:
     820        except ValidationError as e:
    821821            errors = e.update_error_dict(errors)
    822822
    823823        if errors:
    class Model(object):  
    842842                continue
    843843            try:
    844844                setattr(self, f.attname, f.clean(raw_value, self))
    845             except ValidationError, e:
     845            except ValidationError as e:
    846846                errors[f.name] = e.messages
    847847
    848848        if errors:
  • django/db/models/fields/__init__.py

    diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py
    index 22546c2..67a4381 100644
    a b class Field(object):  
    152152        for v in self.validators:
    153153            try:
    154154                v(value)
    155             except exceptions.ValidationError, e:
     155            except exceptions.ValidationError as e:
    156156                if hasattr(e, 'code') and e.code in self.error_messages:
    157157                    message = self.error_messages[e.code]
    158158                    if e.params:
  • django/db/models/query.py

    diff --git a/django/db/models/query.py b/django/db/models/query.py
    index 44acadf..5c68237 100644
    a b class QuerySet(object):  
    205205            qs = self._clone()
    206206            qs.query.set_limits(k, k + 1)
    207207            return list(qs)[0]
    208         except self.model.DoesNotExist, e:
     208        except self.model.DoesNotExist as e:
    209209            raise IndexError(e.args)
    210210
    211211    def __and__(self, other):
    class QuerySet(object):  
    449449                obj.save(force_insert=True, using=self.db)
    450450                transaction.savepoint_commit(sid, using=self.db)
    451451                return obj, True
    452             except IntegrityError, e:
     452            except IntegrityError as e:
    453453                transaction.savepoint_rollback(sid, using=self.db)
    454454                exc_info = sys.exc_info()
    455455                try:
  • django/db/models/sql/query.py

    diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py
    index 693dde3..bc7512f 100644
    a b class Query(object):  
    11201120                    parts, opts, alias, True, allow_many, allow_explicit_fk=True,
    11211121                    can_reuse=can_reuse, negate=negate,
    11221122                    process_extras=process_extras)
    1123         except MultiJoin, e:
     1123        except MultiJoin as e:
    11241124            self.split_exclude(filter_expr, LOOKUP_SEP.join(parts[:e.level]),
    11251125                    can_reuse)
    11261126            return
  • django/db/utils.py

    diff --git a/django/db/utils.py b/django/db/utils.py
    index 3f5b86e..2b6ae2c 100644
    a b def load_backend(backend_name):  
    2222    # Look for a fully qualified database backend name
    2323    try:
    2424        return import_module('.base', backend_name)
    25     except ImportError, e_user:
     25    except ImportError as e_user:
    2626        # The database backend wasn't found. Display a helpful error message
    2727        # listing all possible (built-in) database backends.
    2828        backend_dir = os.path.join(os.path.dirname(__file__), 'backends')
    class ConnectionRouter(object):  
    112112                try:
    113113                    module_name, klass_name = r.rsplit('.', 1)
    114114                    module = import_module(module_name)
    115                 except ImportError, e:
     115                except ImportError as e:
    116116                    raise ImproperlyConfigured('Error importing database router %s: "%s"' % (klass_name, e))
    117117                try:
    118118                    router_class = getattr(module, klass_name)
  • django/dispatch/dispatcher.py

    diff --git a/django/dispatch/dispatcher.py b/django/dispatch/dispatcher.py
    index ed9da57..0903c3a 100644
    a b class Signal(object):  
    205205        for receiver in self._live_receivers(_make_id(sender)):
    206206            try:
    207207                response = receiver(signal=self, sender=sender, **named)
    208             except Exception, err:
     208            except Exception as err:
    209209                responses.append((receiver, err))
    210210            else:
    211211                responses.append((receiver, response))
  • django/dispatch/saferef.py

    diff --git a/django/dispatch/saferef.py b/django/dispatch/saferef.py
    index 1c7d164..364c13e 100644
    a b class BoundMethodWeakref(object):  
    119119                try:
    120120                    if callable( function ):
    121121                        function( self )
    122                 except Exception, e:
     122                except Exception as e:
    123123                    try:
    124124                        traceback.print_exc()
    125                     except AttributeError, err:
     125                    except AttributeError as err:
    126126                        print '''Exception during saferef %s cleanup function %s: %s'''%(
    127127                            self, function, e
    128128                        )
  • django/forms/fields.py

    diff --git a/django/forms/fields.py b/django/forms/fields.py
    index 96ecabf..5d9d581 100644
    a b class Field(object):  
    132132        for v in self.validators:
    133133            try:
    134134                v(value)
    135             except ValidationError, e:
     135            except ValidationError as e:
    136136                if hasattr(e, 'code') and e.code in self.error_messages:
    137137                    message = self.error_messages[e.code]
    138138                    if e.params:
    class MultiValueField(Field):  
    898898                raise ValidationError(self.error_messages['required'])
    899899            try:
    900900                clean_data.append(field.clean(field_value))
    901             except ValidationError, e:
     901            except ValidationError as e:
    902902                # Collect all validation errors in a single list, which we'll
    903903                # raise at the end of clean(), rather than raising a single
    904904                # exception for the first error we encounter.
  • django/forms/forms.py

    diff --git a/django/forms/forms.py b/django/forms/forms.py
    index 94eb22d..09663d1 100644
    a b class BaseForm(StrAndUnicode):  
    289289                if hasattr(self, 'clean_%s' % name):
    290290                    value = getattr(self, 'clean_%s' % name)()
    291291                    self.cleaned_data[name] = value
    292             except ValidationError, e:
     292            except ValidationError as e:
    293293                self._errors[name] = self.error_class(e.messages)
    294294                if name in self.cleaned_data:
    295295                    del self.cleaned_data[name]
    class BaseForm(StrAndUnicode):  
    297297    def _clean_form(self):
    298298        try:
    299299            self.cleaned_data = self.clean()
    300         except ValidationError, e:
     300        except ValidationError as e:
    301301            self._errors[NON_FIELD_ERRORS] = self.error_class(e.messages)
    302302
    303303    def _post_clean(self):
  • django/forms/formsets.py

    diff --git a/django/forms/formsets.py b/django/forms/formsets.py
    index dcd2f01..739a9d4 100644
    a b class BaseFormSet(StrAndUnicode):  
    291291        # Give self.clean() a chance to do cross-form validation.
    292292        try:
    293293            self.clean()
    294         except ValidationError, e:
     294        except ValidationError as e:
    295295            self._non_form_errors = self.error_class(e.messages)
    296296
    297297    def clean(self):
  • django/forms/models.py

    diff --git a/django/forms/models.py b/django/forms/models.py
    index cd8f027..ea80f8d 100644
    a b class BaseModelForm(BaseForm):  
    324324        # Clean the model instance's fields.
    325325        try:
    326326            self.instance.clean_fields(exclude=exclude)
    327         except ValidationError, e:
     327        except ValidationError as e:
    328328            self._update_errors(e.message_dict)
    329329
    330330        # Call the model instance's clean method.
    331331        try:
    332332            self.instance.clean()
    333         except ValidationError, e:
     333        except ValidationError as e:
    334334            self._update_errors({NON_FIELD_ERRORS: e.messages})
    335335
    336336        # Validate uniqueness if needed.
    class BaseModelForm(BaseForm):  
    345345        exclude = self._get_validation_exclusions()
    346346        try:
    347347            self.instance.validate_unique(exclude=exclude)
    348         except ValidationError, e:
     348        except ValidationError as e:
    349349            self._update_errors(e.message_dict)
    350350
    351351    def save(self, commit=True):
  • django/forms/util.py

    diff --git a/django/forms/util.py b/django/forms/util.py
    index 886f08e..1f3e290 100644
    a b def from_current_timezone(value):  
    6666        current_timezone = timezone.get_current_timezone()
    6767        try:
    6868            return timezone.make_aware(value, current_timezone)
    69         except Exception, e:
     69        except Exception as e:
    7070            raise ValidationError(_('%(datetime)s couldn\'t be interpreted '
    7171                                    'in time zone %(current_timezone)s; it '
    7272                                    'may be ambiguous or it may not exist.')
  • django/http/__init__.py

    diff --git a/django/http/__init__.py b/django/http/__init__.py
    index 94478ae..1e371bd 100644
    a b class HttpRequest(object):  
    326326                raise Exception("You cannot access body after reading from request's data stream")
    327327            try:
    328328                self._body = self.read()
    329             except IOError, e:
     329            except IOError as e:
    330330                raise UnreadablePostError, e, sys.exc_traceback
    331331            self._stream = StringIO(self._body)
    332332        return self._body
    class HttpResponse(object):  
    592592            if isinstance(value, unicode):
    593593                try:
    594594                    value = value.encode('us-ascii')
    595                 except UnicodeError, e:
     595                except UnicodeError as e:
    596596                    e.reason += ', HTTP response headers must be in US-ASCII format'
    597597                    raise
    598598            else:
  • django/http/multipartparser.py

    diff --git a/django/http/multipartparser.py b/django/http/multipartparser.py
    index 477a08c..180ec34 100644
    a b class MultiPartParser(object):  
    196196                                # We only special-case base64 transfer encoding
    197197                                try:
    198198                                    chunk = str(chunk).decode('base64')
    199                                 except Exception, e:
     199                                except Exception as e:
    200200                                    # Since this is only a chunk, any error is an unfixable error.
    201201                                    raise MultiPartParserError("Could not decode base64 data: %r" % e)
    202202
    class MultiPartParser(object):  
    209209                                    # If the chunk received by the handler is None, then don't continue.
    210210                                    break
    211211
    212                     except SkipFile, e:
     212                    except SkipFile as e:
    213213                        # Just use up the rest of this file...
    214214                        exhaust(field_stream)
    215215                    else:
    class MultiPartParser(object):  
    218218                else:
    219219                    # If this is neither a FIELD or a FILE, just exhaust the stream.
    220220                    exhaust(stream)
    221         except StopUpload, e:
     221        except StopUpload as e:
    222222            if not e.connection_reset:
    223223                exhaust(self._input_data)
    224224        else:
  • django/template/base.py

    diff --git a/django/template/base.py b/django/template/base.py
    index e2fc66b..f08313c 100644
    a b class Parser(object):  
    265265                    self.invalid_block_tag(token, command, parse_until)
    266266                try:
    267267                    compiled_result = compile_func(self, token)
    268                 except TemplateSyntaxError, e:
     268                except TemplateSyntaxError as e:
    269269                    if not self.compile_function_error(token, e):
    270270                        raise
    271271                self.extend_nodelist(nodelist, compiled_result, token)
    class Variable(object):  
    774774                            # GOTCHA: This will also catch any TypeError
    775775                            # raised in the function itself.
    776776                            current = settings.TEMPLATE_STRING_IF_INVALID  # invalid method call
    777         except Exception, e:
     777        except Exception as e:
    778778            if getattr(e, 'silent_variable_failure', False):
    779779                current = settings.TEMPLATE_STRING_IF_INVALID
    780780            else:
    def import_library(taglib_module):  
    12371237    """
    12381238    try:
    12391239        mod = import_module(taglib_module)
    1240     except ImportError, e:
     1240    except ImportError as e:
    12411241        # If the ImportError is because the taglib submodule does not exist,
    12421242        # that's not an error that should be raised. If the submodule exists
    12431243        # and raised an ImportError on the attempt to load it, that we want
  • django/template/context.py

    diff --git a/django/template/context.py b/django/template/context.py
    index bbd38ad..db24551 100644
    a b def get_standard_processors():  
    147147            module, attr = path[:i], path[i+1:]
    148148            try:
    149149                mod = import_module(module)
    150             except ImportError, e:
     150            except ImportError as e:
    151151                raise ImproperlyConfigured('Error importing request processor module %s: "%s"' % (module, e))
    152152            try:
    153153                func = getattr(mod, attr)
  • django/template/debug.py

    diff --git a/django/template/debug.py b/django/template/debug.py
    index 74aa82b..e8fd0b0 100644
    a b class DebugNodeList(NodeList):  
    7272    def render_node(self, node, context):
    7373        try:
    7474            return node.render(context)
    75         except Exception, e:
     75        except Exception as e:
    7676            if not hasattr(e, 'django_template_source'):
    7777                e.django_template_source = node.source
    7878            raise
    class DebugVariableNode(VariableNode):  
    8787            output = force_unicode(output)
    8888        except UnicodeDecodeError:
    8989            return ''
    90         except Exception, e:
     90        except Exception as e:
    9191            if not hasattr(e, 'django_template_source'):
    9292                e.django_template_source = self.source
    9393            raise
  • django/template/defaultfilters.py

    diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py
    index f93e799..ea7d5e4 100644
    a b def pprint(value):  
    892892    """A wrapper around pprint.pprint -- for debugging, really."""
    893893    try:
    894894        return pformat(value)
    895     except Exception, e:
     895    except Exception as e:
    896896        return u"Error in formatting: %s" % force_unicode(e, errors="replace")
  • django/template/defaulttags.py

    diff --git a/django/template/defaulttags.py b/django/template/defaulttags.py
    index 954c5d6..00cf08c 100644
    a b class ForNode(Node):  
    183183                for node in self.nodelist_loop:
    184184                    try:
    185185                        nodelist.append(node.render(context))
    186                     except Exception, e:
     186                    except Exception as e:
    187187                        if not hasattr(e, 'django_template_source'):
    188188                            e.django_template_source = node.source
    189189                        raise
    class SsiNode(Node):  
    340340            try:
    341341                t = Template(output, name=filepath)
    342342                return t.render(context)
    343             except TemplateSyntaxError, e:
     343            except TemplateSyntaxError as e:
    344344                if settings.DEBUG:
    345345                    return "[Included template had syntax error: %s]" % e
    346346                else:
    class URLNode(Node):  
    409409        url = ''
    410410        try:
    411411            url = reverse(view_name, args=args, kwargs=kwargs, current_app=context.current_app)
    412         except NoReverseMatch, e:
     412        except NoReverseMatch as e:
    413413            if settings.SETTINGS_MODULE:
    414414                project_name = settings.SETTINGS_MODULE.split('.')[0]
    415415                try:
    def load(parser, token):  
    10151015        try:
    10161016            taglib = bits[-1]
    10171017            lib = get_library(taglib)
    1018         except InvalidTemplateLibrary, e:
     1018        except InvalidTemplateLibrary as e:
    10191019            raise TemplateSyntaxError("'%s' is not a valid tag library: %s" %
    10201020                                      (taglib, e))
    10211021        else:
    def load(parser, token):  
    10381038            try:
    10391039                lib = get_library(taglib)
    10401040                parser.add_library(lib)
    1041             except InvalidTemplateLibrary, e:
     1041            except InvalidTemplateLibrary as e:
    10421042                raise TemplateSyntaxError("'%s' is not a valid tag library: %s" %
    10431043                                          (taglib, e))
    10441044    return LoadNode()
  • django/template/loader.py

    diff --git a/django/template/loader.py b/django/template/loader.py
    index 4185017..b6d62cc 100644
    a b def find_template_loader(loader):  
    9393        module, attr = loader.rsplit('.', 1)
    9494        try:
    9595            mod = import_module(module)
    96         except ImportError, e:
     96        except ImportError as e:
    9797            raise ImproperlyConfigured('Error importing template source loader %s: "%s"' % (loader, e))
    9898        try:
    9999            TemplateLoader = getattr(mod, attr)
    100         except AttributeError, e:
     100        except AttributeError as e:
    101101            raise ImproperlyConfigured('Error importing template source loader %s: "%s"' % (loader, e))
    102102
    103103        if hasattr(TemplateLoader, 'load_template_source'):
    def select_template(template_name_list):  
    185185    for template_name in template_name_list:
    186186        try:
    187187            return get_template(template_name)
    188         except TemplateDoesNotExist, e:
     188        except TemplateDoesNotExist as e:
    189189            if e.args[0] not in not_found:
    190190                not_found.append(e.args[0])
    191191            continue
  • django/template/loaders/app_directories.py

    diff --git a/django/template/loaders/app_directories.py b/django/template/loaders/app_directories.py
    index b0560b4..1ddb18e 100644
    a b app_template_dirs = []  
    1919for app in settings.INSTALLED_APPS:
    2020    try:
    2121        mod = import_module(app)
    22     except ImportError, e:
     22    except ImportError as e:
    2323        raise ImproperlyConfigured('ImportError %s: %s' % (app, e.args[0]))
    2424    template_dir = os.path.join(os.path.dirname(mod.__file__), 'templates')
    2525    if os.path.isdir(template_dir):
  • django/test/_doctest.py

    diff --git a/django/test/_doctest.py b/django/test/_doctest.py
    index fe9b2f1..af2f409 100644
    a b class DebugRunner(DocTestRunner):  
    16261626         ...                                    {}, 'foo', 'foo.py', 0)
    16271627         >>> try:
    16281628         ...     runner.run(test)
    1629          ... except UnexpectedException, failure:
     1629         ... except UnexpectedException as failure:
    16301630         ...     pass
    16311631
    16321632         >>> failure.test is test
    class DebugRunner(DocTestRunner):  
    16541654
    16551655         >>> try:
    16561656         ...    runner.run(test)
    1657          ... except DocTestFailure, failure:
     1657         ... except DocTestFailure as failure:
    16581658         ...    pass
    16591659
    16601660       DocTestFailure objects provide access to the test:
    class DocTestCase(unittest.TestCase):  
    21642164             >>> case = DocTestCase(test)
    21652165             >>> try:
    21662166             ...     case.debug()
    2167              ... except UnexpectedException, failure:
     2167             ... except UnexpectedException as failure:
    21682168             ...     pass
    21692169
    21702170           The UnexpectedException contains the test, the example, and
    class DocTestCase(unittest.TestCase):  
    21932193
    21942194             >>> try:
    21952195             ...    case.debug()
    2196              ... except DocTestFailure, failure:
     2196             ... except DocTestFailure as failure:
    21972197             ...    pass
    21982198
    21992199           DocTestFailure objects provide access to the test:
  • django/test/client.py

    diff --git a/django/test/client.py b/django/test/client.py
    index 6f3b73d..69f72fd 100644
    a b class Client(RequestFactory):  
    379379
    380380            try:
    381381                response = self.handler(environ)
    382             except TemplateDoesNotExist, e:
     382            except TemplateDoesNotExist as e:
    383383                # If the view raises an exception, Django will attempt to show
    384384                # the 500.html template. If that template is not available,
    385385                # we should ignore the error in favor of re-raising the
  • django/test/testcases.py

    diff --git a/django/test/testcases.py b/django/test/testcases.py
    index b5e1dc0..7885225 100644
    a b def restore_transaction_methods():  
    8585def assert_and_parse_html(self, html, user_msg, msg):
    8686    try:
    8787        dom = parse_html(html)
    88     except HTMLParseError, e:
     88    except HTMLParseError as e:
    8989        standardMsg = u'%s\n%s' % (msg, e.msg)
    9090        self.fail(self._formatMessage(user_msg, standardMsg))
    9191    return dom
    class LiveServerThread(threading.Thread):  
    10361036                try:
    10371037                    self.httpd = StoppableWSGIServer(
    10381038                        (self.host, port), QuietWSGIRequestHandler)
    1039                 except WSGIServerException, e:
     1039                except WSGIServerException as e:
    10401040                    if sys.version_info < (2, 6):
    10411041                        error_code = e.args[0].args[0]
    10421042                    else:
    class LiveServerThread(threading.Thread):  
    10591059            self.httpd.set_app(handler)
    10601060            self.is_ready.set()
    10611061            self.httpd.serve_forever()
    1062         except Exception, e:
     1062        except Exception as e:
    10631063            self.error = e
    10641064            self.is_ready.set()
    10651065
  • django/utils/daemonize.py

    diff --git a/django/utils/daemonize.py b/django/utils/daemonize.py
    index 68e5392..a9d5128 100644
    a b if os.name == 'posix':  
    99        try:
    1010            if os.fork() > 0:
    1111                sys.exit(0)     # kill off parent
    12         except OSError, e:
     12        except OSError as e:
    1313            sys.stderr.write("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror))
    1414            sys.exit(1)
    1515        os.setsid()
    if os.name == 'posix':  
    2020        try:
    2121            if os.fork() > 0:
    2222                os._exit(0)
    23         except OSError, e:
     23        except OSError as e:
    2424            sys.stderr.write("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror))
    2525            os._exit(1)
    2626
  • django/utils/decorators.py

    diff --git a/django/utils/decorators.py b/django/utils/decorators.py
    index 22f33a7..e653a73 100644
    a b def make_middleware_decorator(middleware_class):  
    8989                        return result
    9090                try:
    9191                    response = view_func(request, *args, **kwargs)
    92                 except Exception, e:
     92                except Exception as e:
    9393                    if hasattr(middleware, 'process_exception'):
    9494                        result = middleware.process_exception(request, e)
    9595                        if result is not None:
  • django/utils/dictconfig.py

    diff --git a/django/utils/dictconfig.py b/django/utils/dictconfig.py
    index 42fbd93..ae797af 100644
    a b class DictConfigurator(BaseConfigurator):  
    297297                                level = handler_config.get('level', None)
    298298                                if level:
    299299                                    handler.setLevel(_checkLevel(level))
    300                             except StandardError, e:
     300                            except StandardError as e:
    301301                                raise ValueError('Unable to configure handler '
    302302                                                 '%r: %s' % (name, e))
    303303                loggers = config.get('loggers', EMPTY_DICT)
    304304                for name in loggers:
    305305                    try:
    306306                        self.configure_logger(name, loggers[name], True)
    307                     except StandardError, e:
     307                    except StandardError as e:
    308308                        raise ValueError('Unable to configure logger '
    309309                                         '%r: %s' % (name, e))
    310310                root = config.get('root', None)
    311311                if root:
    312312                    try:
    313313                        self.configure_root(root, True)
    314                     except StandardError, e:
     314                    except StandardError as e:
    315315                        raise ValueError('Unable to configure root '
    316316                                         'logger: %s' % e)
    317317            else:
    class DictConfigurator(BaseConfigurator):  
    326326                    try:
    327327                        formatters[name] = self.configure_formatter(
    328328                                                            formatters[name])
    329                     except StandardError, e:
     329                    except StandardError as e:
    330330                        raise ValueError('Unable to configure '
    331331                                         'formatter %r: %s' % (name, e))
    332332                # Next, do filters - they don't refer to anything else, either
    class DictConfigurator(BaseConfigurator):  
    334334                for name in filters:
    335335                    try:
    336336                        filters[name] = self.configure_filter(filters[name])
    337                     except StandardError, e:
     337                    except StandardError as e:
    338338                        raise ValueError('Unable to configure '
    339339                                         'filter %r: %s' % (name, e))
    340340
    class DictConfigurator(BaseConfigurator):  
    347347                        handler = self.configure_handler(handlers[name])
    348348                        handler.name = name
    349349                        handlers[name] = handler
    350                     except StandardError, e:
     350                    except StandardError as e:
    351351                        raise ValueError('Unable to configure handler '
    352352                                         '%r: %s' % (name, e))
    353353                # Next, do loggers - they refer to handlers and filters
    class DictConfigurator(BaseConfigurator):  
    386386                        existing.remove(name)
    387387                    try:
    388388                        self.configure_logger(name, loggers[name])
    389                     except StandardError, e:
     389                    except StandardError as e:
    390390                        raise ValueError('Unable to configure logger '
    391391                                         '%r: %s' % (name, e))
    392392
    class DictConfigurator(BaseConfigurator):  
    409409                if root:
    410410                    try:
    411411                        self.configure_root(root)
    412                     except StandardError, e:
     412                    except StandardError as e:
    413413                        raise ValueError('Unable to configure root '
    414414                                         'logger: %s' % e)
    415415        finally:
    class DictConfigurator(BaseConfigurator):  
    421421            factory = config['()'] # for use in exception handler
    422422            try:
    423423                result = self.configure_custom(config)
    424             except TypeError, te:
     424            except TypeError as te:
    425425                if "'format'" not in str(te):
    426426                    raise
    427427                #Name of parameter changed from fmt to format.
    class DictConfigurator(BaseConfigurator):  
    451451        for f in filters:
    452452            try:
    453453                filterer.addFilter(self.config['filters'][f])
    454             except StandardError, e:
     454            except StandardError as e:
    455455                raise ValueError('Unable to add filter %r: %s' % (f, e))
    456456
    457457    def configure_handler(self, config):
    class DictConfigurator(BaseConfigurator):  
    460460        if formatter:
    461461            try:
    462462                formatter = self.config['formatters'][formatter]
    463             except StandardError, e:
     463            except StandardError as e:
    464464                raise ValueError('Unable to set formatter '
    465465                                 '%r: %s' % (formatter, e))
    466466        level = config.pop('level', None)
    class DictConfigurator(BaseConfigurator):  
    477477                'target' in config:
    478478                try:
    479479                    config['target'] = self.config['handlers'][config['target']]
    480                 except StandardError, e:
     480                except StandardError as e:
    481481                    raise ValueError('Unable to set target handler '
    482482                                     '%r: %s' % (config['target'], e))
    483483            elif issubclass(klass, logging.handlers.SMTPHandler) and\
    class DictConfigurator(BaseConfigurator):  
    490490        kwargs = dict([(k, config[k]) for k in config if valid_ident(k)])
    491491        try:
    492492            result = factory(**kwargs)
    493         except TypeError, te:
     493        except TypeError as te:
    494494            if "'stream'" not in str(te):
    495495                raise
    496496            #The argument name changed from strm to stream
    class DictConfigurator(BaseConfigurator):  
    512512        for h in handlers:
    513513            try:
    514514                logger.addHandler(self.config['handlers'][h])
    515             except StandardError, e:
     515            except StandardError as e:
    516516                raise ValueError('Unable to add handler %r: %s' % (h, e))
    517517
    518518    def common_logger_config(self, logger, config, incremental=False):
  • django/utils/encoding.py

    diff --git a/django/utils/encoding.py b/django/utils/encoding.py
    index 36e0da2..d9b5944 100644
    a b def force_unicode(s, encoding='utf-8', strings_only=False, errors='strict'):  
    8888            # errors), so that if s is a SafeString, it ends up being a
    8989            # SafeUnicode at the end.
    9090            s = s.decode(encoding, errors)
    91     except UnicodeDecodeError, e:
     91    except UnicodeDecodeError as e:
    9292        if not isinstance(s, Exception):
    9393            raise DjangoUnicodeDecodeError(s, *e.args)
    9494        else:
  • django/views/debug.py

    diff --git a/django/views/debug.py b/django/views/debug.py
    index b549959..14a151f 100644
    a b def get_exception_reporter_filter(request):  
    7777        modname, classname = modpath.rsplit('.', 1)
    7878        try:
    7979            mod = import_module(modname)
    80         except ImportError, e:
     80        except ImportError as e:
    8181            raise ImproperlyConfigured(
    8282            'Error importing default exception reporter filter %s: "%s"' % (modpath, e))
    8383        try:
  • extras/csrf_migration_helper.py

    diff --git a/extras/csrf_migration_helper.py b/extras/csrf_migration_helper.py
    index 94b5a20..0e13163 100755
    a b class Template(object):  
    173173            fd = open(self.absolute_filename)
    174174            try:
    175175                content = fd.read().decode(TEMPLATE_ENCODING)
    176             except UnicodeDecodeError, e:
     176            except UnicodeDecodeError as e:
    177177                message = '%s in %s' % (
    178178                    e[4], self.absolute_filename.encode('UTF-8', 'ignore'))
    179179                raise UnicodeDecodeError(*(e.args[:4] + (message,)))
  • tests/modeltests/basic/tests.py

    diff --git a/tests/modeltests/basic/tests.py b/tests/modeltests/basic/tests.py
    index f9141dc..42192e0 100644
    a b class ModelTest(TestCase):  
    374374        try:
    375375            Article.objects.all()[0:1] & Article.objects.all()[4:5]
    376376            self.fail('Should raise an AssertionError')
    377         except AssertionError, e:
     377        except AssertionError as e:
    378378            self.assertEqual(str(e), "Cannot combine queries once a slice has been taken.")
    379         except Exception, e:
     379        except Exception as e:
    380380            self.fail('Should raise an AssertionError, not %s' % e)
    381381
    382382        # Negative slices are not supported, due to database constraints.
    class ModelTest(TestCase):  
    384384        try:
    385385            Article.objects.all()[-1]
    386386            self.fail('Should raise an AssertionError')
    387         except AssertionError, e:
     387        except AssertionError as e:
    388388            self.assertEqual(str(e), "Negative indexing is not supported.")
    389         except Exception, e:
     389        except Exception as e:
    390390            self.fail('Should raise an AssertionError, not %s' % e)
    391391
    392392        error = None
    393393        try:
    394394            Article.objects.all()[0:-5]
    395         except Exception, e:
     395        except Exception as e:
    396396            error = e
    397397        self.assertTrue(isinstance(error, AssertionError))
    398398        self.assertEqual(str(error), "Negative indexing is not supported.")
  • tests/modeltests/get_or_create/tests.py

    diff --git a/tests/modeltests/get_or_create/tests.py b/tests/modeltests/get_or_create/tests.py
    index f98f0e6..1e300fb 100644
    a b class GetOrCreateTests(TestCase):  
    6060        # the actual traceback. Refs #16340.
    6161        try:
    6262            ManualPrimaryKeyTest.objects.get_or_create(id=1, data="Different")
    63         except IntegrityError, e:
     63        except IntegrityError as e:
    6464            formatted_traceback = traceback.format_exc()
    6565            self.assertIn('obj.save', formatted_traceback)
    6666
  • tests/modeltests/invalid_models/tests.py

    diff --git a/tests/modeltests/invalid_models/tests.py b/tests/modeltests/invalid_models/tests.py
    index dac562c..a1084c6 100644
    a b class InvalidModelTestCase(unittest.TestCase):  
    3535
    3636        try:
    3737            module = load_app("modeltests.invalid_models.invalid_models")
    38         except Exception, e:
     38        except Exception as e:
    3939            self.fail('Unable to load invalid model module')
    4040
    4141        count = get_validation_errors(self.stdout, module)
  • tests/modeltests/lookup/tests.py

    diff --git a/tests/modeltests/lookup/tests.py b/tests/modeltests/lookup/tests.py
    index 3571e21..ccd7863 100644
    a b class LookupTests(TestCase):  
    468468        try:
    469469            Article.objects.filter(pub_date_year='2005').count()
    470470            self.fail('FieldError not raised')
    471         except FieldError, ex:
     471        except FieldError as ex:
    472472            self.assertEqual(str(ex), "Cannot resolve keyword 'pub_date_year' "
    473473                             "into field. Choices are: author, headline, id, pub_date, tag")
    474474        try:
    475475            Article.objects.filter(headline__starts='Article')
    476476            self.fail('FieldError not raised')
    477         except FieldError, ex:
     477        except FieldError as ex:
    478478            self.assertEqual(str(ex), "Join on field 'headline' not permitted. "
    479479                             "Did you misspell 'starts' for the lookup type?")
    480480
  • tests/modeltests/select_for_update/tests.py

    diff --git a/tests/modeltests/select_for_update/tests.py b/tests/modeltests/select_for_update/tests.py
    index 65bc13a..dba7889 100644
    a b class SelectForUpdateTests(TransactionTestCase):  
    169169            people[0].name = 'Fred'
    170170            people[0].save()
    171171            transaction.commit()
    172         except DatabaseError, e:
     172        except DatabaseError as e:
    173173            status.append(e)
    174         except Exception, e:
     174        except Exception as e:
    175175            raise
    176176        finally:
    177177            # This method is run in a separate thread. It uses its own
    class SelectForUpdateTests(TransactionTestCase):  
    246246                        )
    247247                    )
    248248                )
    249             except DatabaseError, e:
     249            except DatabaseError as e:
    250250                status.append(e)
    251251            finally:
    252252                # This method is run in a separate thread. It uses its own
  • tests/modeltests/validation/models.py

    diff --git a/tests/modeltests/validation/models.py b/tests/modeltests/validation/models.py
    index 8010701..7791a09 100644
    a b try:  
    100100    class MultipleAutoFields(models.Model):
    101101        auto1 = models.AutoField(primary_key=True)
    102102        auto2 = models.AutoField(primary_key=True)
    103 except AssertionError, assertion_error:
     103except AssertionError as assertion_error:
    104104    pass # Fail silently
    105105assert str(assertion_error) == u"A model can't have more than one AutoField."
     106 No newline at end of file
  • tests/modeltests/validation/test_error_messages.py

    diff --git a/tests/modeltests/validation/test_error_messages.py b/tests/modeltests/validation/test_error_messages.py
    index 4a2ad1f..04ad7aa 100644
    a b class ValidationMessagesTest(TestCase):  
    1010        self.assertRaises(ValidationError, f.clean, 'foo', None)
    1111        try:
    1212            f.clean('foo', None)
    13         except ValidationError, e:
     13        except ValidationError as e:
    1414            self.assertEqual(e.messages, [u"'foo' value must be an integer."])
    1515        # primary_key must be True. Refs #12467.
    1616        self.assertRaises(AssertionError, models.AutoField, 'primary_key', False)
    1717        try:
    1818            models.AutoField(primary_key=False)
    19         except AssertionError, e:
     19        except AssertionError as e:
    2020            self.assertEqual(str(e), "AutoFields must have primary_key=True.")
    2121
    2222    def test_integer_field_raises_error_message(self):
    class ValidationMessagesTest(TestCase):  
    2424        self.assertRaises(ValidationError, f.clean, 'foo', None)
    2525        try:
    2626            f.clean('foo', None)
    27         except ValidationError, e:
     27        except ValidationError as e:
    2828            self.assertEqual(e.messages, [u"'foo' value must be an integer."])
    2929
    3030    def test_boolean_field_raises_error_message(self):
    class ValidationMessagesTest(TestCase):  
    3232        self.assertRaises(ValidationError, f.clean, 'foo', None)
    3333        try:
    3434            f.clean('foo', None)
    35         except ValidationError, e:
     35        except ValidationError as e:
    3636            self.assertEqual(e.messages,
    3737                        [u"'foo' value must be either True or False."])
    3838
    class ValidationMessagesTest(TestCase):  
    4141        self.assertRaises(ValidationError, f.clean, 'foo', None)
    4242        try:
    4343            f.clean('foo', None)
    44         except ValidationError, e:
     44        except ValidationError as e:
    4545            self.assertEqual(e.messages, [u"'foo' value must be a float."])
    4646
    4747    def test_decimal_field_raises_error_message(self):
    class ValidationMessagesTest(TestCase):  
    4949        self.assertRaises(ValidationError, f.clean, 'foo', None)
    5050        try:
    5151            f.clean('foo', None)
    52         except ValidationError, e:
     52        except ValidationError as e:
    5353            self.assertEqual(e.messages,
    5454                        [u"'foo' value must be a decimal number."])
    5555
    class ValidationMessagesTest(TestCase):  
    5858        self.assertRaises(ValidationError, f.clean, 'foo', None)
    5959        try:
    6060            f.clean('foo', None)
    61         except ValidationError, e:
     61        except ValidationError as e:
    6262            self.assertEqual(e.messages,
    6363                        [u"'foo' value must be either None, True or False."])
    6464
    class ValidationMessagesTest(TestCase):  
    6767        self.assertRaises(ValidationError, f.clean, 'foo', None)
    6868        try:
    6969            f.clean('foo', None)
    70         except ValidationError, e:
     70        except ValidationError as e:
    7171            self.assertEqual(e.messages, [
    7272                u"'foo' value has an invalid date format. "
    7373                u"It must be in YYYY-MM-DD format."])
    class ValidationMessagesTest(TestCase):  
    7575        self.assertRaises(ValidationError, f.clean, 'aaaa-10-10', None)
    7676        try:
    7777            f.clean('aaaa-10-10', None)
    78         except ValidationError, e:
     78        except ValidationError as e:
    7979            self.assertEqual(e.messages, [
    8080                u"'aaaa-10-10' value has an invalid date format. "
    8181                u"It must be in YYYY-MM-DD format."])
    class ValidationMessagesTest(TestCase):  
    8383        self.assertRaises(ValidationError, f.clean, '2011-13-10', None)
    8484        try:
    8585            f.clean('2011-13-10', None)
    86         except ValidationError, e:
     86        except ValidationError as e:
    8787            self.assertEqual(e.messages, [
    8888                u"'2011-13-10' value has the correct format (YYYY-MM-DD) "
    8989                u"but it is an invalid date."])
    class ValidationMessagesTest(TestCase):  
    9191        self.assertRaises(ValidationError, f.clean, '2011-10-32', None)
    9292        try:
    9393            f.clean('2011-10-32', None)
    94         except ValidationError, e:
     94        except ValidationError as e:
    9595            self.assertEqual(e.messages, [
    9696                u"'2011-10-32' value has the correct format (YYYY-MM-DD) "
    9797                u"but it is an invalid date."])
    class ValidationMessagesTest(TestCase):  
    102102        self.assertRaises(ValidationError, f.clean, 'foo', None)
    103103        try:
    104104            f.clean('foo', None)
    105         except ValidationError, e:
     105        except ValidationError as e:
    106106            self.assertEqual(e.messages, [
    107107                u"'foo' value has an invalid format. It must be "
    108108                u"in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."])
    class ValidationMessagesTest(TestCase):  
    111111        self.assertRaises(ValidationError, f.clean, '2011-10-32', None)
    112112        try:
    113113            f.clean('2011-10-32', None)
    114         except ValidationError, e:
     114        except ValidationError as e:
    115115            self.assertEqual(e.messages, [
    116116                u"'2011-10-32' value has the correct format "
    117117                u"(YYYY-MM-DD) but it is an invalid date."])
    class ValidationMessagesTest(TestCase):  
    120120        self.assertRaises(ValidationError, f.clean, '2011-10-32 10:10', None)
    121121        try:
    122122            f.clean('2011-10-32 10:10', None)
    123         except ValidationError, e:
     123        except ValidationError as e:
    124124            self.assertEqual(e.messages, [
    125125                u"'2011-10-32 10:10' value has the correct format "
    126126                u"(YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) "
    class ValidationMessagesTest(TestCase):  
    132132        self.assertRaises(ValidationError, f.clean, 'foo', None)
    133133        try:
    134134            f.clean('foo', None)
    135         except ValidationError, e:
     135        except ValidationError as e:
    136136            self.assertEqual(e.messages, [
    137137                u"'foo' value has an invalid format. It must be in "
    138138                u"HH:MM[:ss[.uuuuuu]] format."])
    class ValidationMessagesTest(TestCase):  
    140140        self.assertRaises(ValidationError, f.clean, '25:50', None)
    141141        try:
    142142            f.clean('25:50', None)
    143         except ValidationError, e:
     143        except ValidationError as e:
    144144            self.assertEqual(e.messages, [
    145145                u"'25:50' value has the correct format "
    146146                u"(HH:MM[:ss[.uuuuuu]]) but it is an invalid time."])
  • tests/modeltests/validation/test_unique.py

    diff --git a/tests/modeltests/validation/test_unique.py b/tests/modeltests/validation/test_unique.py
    index 3ae981d..e31698d 100644
    a b class PerformUniqueChecksTest(TestCase):  
    115115        p = FlexibleDatePost(title="Django 1.0 is released")
    116116        try:
    117117            p.full_clean()
    118         except ValidationError, e:
     118        except ValidationError as e:
    119119            self.fail("unique_for_date checks shouldn't trigger when the associated DateField is None.")
    120120
    121121        p = FlexibleDatePost(slug="Django 1.0")
    122122        try:
    123123            p.full_clean()
    124         except ValidationError, e:
     124        except ValidationError as e:
    125125            self.fail("unique_for_year checks shouldn't trigger when the associated DateField is None.")
    126126
    127127        p = FlexibleDatePost(subtitle="Finally")
    128128        try:
    129129            p.full_clean()
    130         except ValidationError, e:
     130        except ValidationError as e:
    131131            self.fail("unique_for_month checks shouldn't trigger when the associated DateField is None.")
    132132
    133133    def test_unique_errors(self):
  • tests/regressiontests/app_loading/tests.py

    diff --git a/tests/regressiontests/app_loading/tests.py b/tests/regressiontests/app_loading/tests.py
    index 5173338..0e66a5a 100644
    a b class EggLoadingTest(TestCase):  
    6161        self.assertRaises(ImportError, load_app, 'broken_app')
    6262        try:
    6363            load_app('broken_app')
    64         except ImportError, e:
     64        except ImportError as e:
    6565            # Make sure the message is indicating the actual
    6666            # problem in the broken app.
    6767            self.assertTrue("modelz" in e.args[0])
  • tests/regressiontests/backends/tests.py

    diff --git a/tests/regressiontests/backends/tests.py b/tests/regressiontests/backends/tests.py
    index cfb662e..e2e712a 100644
    a b class ThreadTests(TestCase):  
    544544                connections['default'] = main_thread_connection
    545545                try:
    546546                    models.Person.objects.get(first_name="John", last_name="Doe")
    547                 except DatabaseError, e:
     547                except DatabaseError as e:
    548548                    exceptions.append(e)
    549549            t = threading.Thread(target=runner, args=[connections['default']])
    550550            t.start()
    class ThreadTests(TestCase):  
    582582            def runner2(other_thread_connection):
    583583                try:
    584584                    other_thread_connection.close()
    585                 except DatabaseError, e:
     585                except DatabaseError as e:
    586586                    exceptions.add(e)
    587587            t2 = threading.Thread(target=runner2, args=[connections['default']])
    588588            t2.start()
    class ThreadTests(TestCase):  
    599599            def runner2(other_thread_connection):
    600600                try:
    601601                    other_thread_connection.close()
    602                 except DatabaseError, e:
     602                except DatabaseError as e:
    603603                    exceptions.add(e)
    604604            # Enable thread sharing
    605605            connections['default'].allow_thread_sharing = True
  • tests/regressiontests/file_uploads/tests.py

    diff --git a/tests/regressiontests/file_uploads/tests.py b/tests/regressiontests/file_uploads/tests.py
    index ffa2017..4e5020d 100644
    a b class FileUploadTests(TestCase):  
    303303        # it raises when there is an attempt to read more than the available bytes:
    304304        try:
    305305            client.FakePayload('a').read(2)
    306         except Exception, reference_error:
     306        except Exception as reference_error:
    307307            pass
    308308
    309309        # install the custom handler that tries to access request.POST
    class FileUploadTests(TestCase):  
    311311
    312312        try:
    313313            response = self.client.post('/file_uploads/upload_errors/', post_data)
    314         except reference_error.__class__, err:
     314        except reference_error.__class__ as err:
    315315            self.failIf(
    316316                str(err) == str(reference_error),
    317317                "Caught a repeated exception that'll cause an infinite loop in file uploads."
    318318            )
    319         except Exception, err:
     319        except Exception as err:
    320320            # CustomUploadError is the error that should have been raised
    321321            self.assertEqual(err.__class__, uploadhandler.CustomUploadError)
    322322
    class DirectoryCreationTests(unittest.TestCase):  
    373373        os.chmod(temp_storage.location, 0500)
    374374        try:
    375375            self.obj.testfile.save('foo.txt', SimpleUploadedFile('foo.txt', 'x'))
    376         except OSError, err:
     376        except OSError as err:
    377377            self.assertEqual(err.errno, errno.EACCES)
    378         except Exception, err:
     378        except Exception as err:
    379379            self.fail("OSError [Errno %s] not raised." % errno.EACCES)
    380380
    381381    def test_not_a_directory(self):
    class DirectoryCreationTests(unittest.TestCase):  
    385385        fd.close()
    386386        try:
    387387            self.obj.testfile.save('foo.txt', SimpleUploadedFile('foo.txt', 'x'))
    388         except IOError, err:
     388        except IOError as err:
    389389            # The test needs to be done on a specific string as IOError
    390390            # is raised even without the patch (just not early enough)
    391391            self.assertEqual(err.args[0],
  • tests/regressiontests/forms/tests/error_messages.py

    diff --git a/tests/regressiontests/forms/tests/error_messages.py b/tests/regressiontests/forms/tests/error_messages.py
    index b7b4e98..9e1a6c9 100644
    a b class AssertFormErrorsMixin(object):  
    1515        try:
    1616            the_callable(*args, **kwargs)
    1717            self.fail("Testing the 'clean' method on %s failed to raise a ValidationError.")
    18         except ValidationError, e:
     18        except ValidationError as e:
    1919            self.assertEqual(e.messages, expected)
    2020
    2121class FormsErrorMessagesTestCase(TestCase, AssertFormErrorsMixin):
  • tests/regressiontests/forms/tests/fields.py

    diff --git a/tests/regressiontests/forms/tests/fields.py b/tests/regressiontests/forms/tests/fields.py
    index 03e0ff6..138d3af 100644
    a b class FieldsTests(SimpleTestCase):  
    660660        self.assertRaises(ValidationError, f.clean, 'http://qa-dev.w3.org/link-testsuite/http.php?code=405') # Method not allowed
    661661        try:
    662662            f.clean('http://www.broken.djangoproject.com') # bad domain
    663         except ValidationError, e:
     663        except ValidationError as e:
    664664            self.assertEqual("[u'This URL appears to be a broken link.']", str(e))
    665665        self.assertRaises(ValidationError, f.clean, 'http://qa-dev.w3.org/link-testsuite/http.php?code=400') # good domain, bad page
    666666        try:
    667667            f.clean('http://google.com/we-love-microsoft.html') # good domain, bad page
    668         except ValidationError, e:
     668        except ValidationError as e:
    669669            self.assertEqual("[u'This URL appears to be a broken link.']", str(e))
    670670
    671671    @verify_exists_urls(('http://www.google.com/',))
    class FieldsTests(SimpleTestCase):  
    719719        # Valid but non-existent IDN
    720720        try:
    721721            f.clean(u'http://broken.עברית.idn.icann.org/')
    722         except ValidationError, e:
     722        except ValidationError as e:
    723723            self.assertEqual("[u'This URL appears to be a broken link.']", str(e))
    724724
    725725    @verify_exists_urls((u'http://xn--hxargifdar.idn.icann.org/%CE%91%CF%81%CF%87%CE%B9%CE%BA%CE%AE_%CF%83%CE%B5%CE%BB%CE%AF%CE%B4%CE%B1',))
  • tests/regressiontests/forms/tests/validators.py

    diff --git a/tests/regressiontests/forms/tests/validators.py b/tests/regressiontests/forms/tests/validators.py
    index cadf660..a4cb324 100644
    a b class TestFieldWithValidators(TestCase):  
    1212        self.assertRaises(ValidationError, field.clean, 'not int nor mail')
    1313        try:
    1414            field.clean('not int nor mail')
    15         except ValidationError, e:
     15        except ValidationError as e:
    1616            self.assertEqual(2, len(e.messages))
  • tests/regressiontests/middleware/tests.py

    diff --git a/tests/regressiontests/middleware/tests.py b/tests/regressiontests/middleware/tests.py
    index 6a1896a..5e48f8d 100644
    a b class CommonMiddlewareTest(TestCase):  
    8888            request)
    8989        try:
    9090            CommonMiddleware().process_request(request)
    91         except RuntimeError, e:
     91        except RuntimeError as e:
    9292            self.assertTrue('end in a slash' in str(e))
    9393        settings.DEBUG = False
    9494
    class CommonMiddlewareTest(TestCase):  
    202202          request)
    203203      try:
    204204          CommonMiddleware().process_request(request)
    205       except RuntimeError, e:
     205      except RuntimeError as e:
    206206          self.assertTrue('end in a slash' in str(e))
    207207      settings.DEBUG = False
    208208
  • tests/regressiontests/middleware_exceptions/tests.py

    diff --git a/tests/regressiontests/middleware_exceptions/tests.py b/tests/regressiontests/middleware_exceptions/tests.py
    index ac5f09a..d1acbfd 100644
    a b class BaseMiddlewareExceptionTest(TestCase):  
    118118    def assert_exceptions_handled(self, url, errors, extra_error=None):
    119119        try:
    120120            response = self.client.get(url)
    121         except TestException, e:
     121        except TestException as e:
    122122            # Test client intentionally re-raises any exceptions being raised
    123123            # during request handling. Hence actual testing that exception was
    124124            # properly handled is done by relying on got_request_exception
    125125            # signal being sent.
    126126            pass
    127         except Exception, e:
     127        except Exception as e:
    128128            if type(extra_error) != type(e):
    129129                self.fail("Unexpected exception: %s" % e)
    130130        self.assertEqual(len(self.exceptions), len(errors))
  • tests/regressiontests/model_fields/tests.py

    diff --git a/tests/regressiontests/model_fields/tests.py b/tests/regressiontests/model_fields/tests.py
    index 8fe67fb..ea1e1c7 100644
    a b class BasicFieldTests(test.TestCase):  
    4444        nullboolean = NullBooleanModel(nbfield=None)
    4545        try:
    4646            nullboolean.full_clean()
    47         except ValidationError, e:
     47        except ValidationError as e:
    4848            self.fail("NullBooleanField failed validation with value of None: %s" % e.messages)
    4949
    5050    def test_field_repr(self):
  • tests/regressiontests/model_forms_regress/tests.py

    diff --git a/tests/regressiontests/model_forms_regress/tests.py b/tests/regressiontests/model_forms_regress/tests.py
    index caf24d3..09da973 100644
    a b class InvalidFieldAndFactory(TestCase):  
    333333                class Meta:
    334334                    model = Person
    335335                    fields = ('name', 'no-field')
    336         except FieldError, e:
     336        except FieldError as e:
    337337            # Make sure the exception contains some reference to the
    338338            # field responsible for the problem.
    339339            self.assertTrue('no-field' in e.args[0])
  • tests/regressiontests/servers/tests.py

    diff --git a/tests/regressiontests/servers/tests.py b/tests/regressiontests/servers/tests.py
    index d237c83..ac92bec 100644
    a b class LiveServerViews(LiveServerBase):  
    164164        """
    165165        try:
    166166            self.urlopen('/')
    167         except urllib2.HTTPError, err:
     167        except urllib2.HTTPError as err:
    168168            self.assertEquals(err.code, 404, 'Expected 404 response')
    169169        else:
    170170            self.fail('Expected 404 response')
  • tests/regressiontests/settings_tests/tests.py

    diff --git a/tests/regressiontests/settings_tests/tests.py b/tests/regressiontests/settings_tests/tests.py
    index a2e6c49..4b0ede3 100644
    a b class ClassDecoratedTestCase(ClassDecoratedTestCaseSuper):  
    6565        """
    6666        try:
    6767            super(ClassDecoratedTestCase, self).test_max_recursion_error()
    68         except RuntimeError, e:
     68        except RuntimeError as e:
    6969            self.fail()
    7070
    7171ClassDecoratedTestCase = override_settings(TEST='override')(ClassDecoratedTestCase)
  • tests/regressiontests/templates/tests.py

    diff --git a/tests/regressiontests/templates/tests.py b/tests/regressiontests/templates/tests.py
    index f74aa75..24dccd6 100644
    a b from .response import (TemplateResponseTest, BaseTemplateResponseTest,  
    4242
    4343try:
    4444    from .loaders import RenderToStringTest, EggLoaderTest
    45 except ImportError, e:
     45except ImportError as e:
    4646    if "pkg_resources" in e.message:
    4747        pass # If setuptools isn't installed, that's fine. Just move on.
    4848    else:
    class Templates(unittest.TestCase):  
    280280            try:
    281281                tmpl = loader.select_template([load_name])
    282282                r = tmpl.render(template.Context({}))
    283             except template.TemplateDoesNotExist, e:
     283            except template.TemplateDoesNotExist as e:
    284284                settings.TEMPLATE_DEBUG = old_td
    285285                self.assertEqual(e.args[0], 'missing.html')
    286286            self.assertEqual(r, None, 'Template rendering unexpectedly succeeded, produced: ->%r<-' % r)
    class Templates(unittest.TestCase):  
    313313            r = None
    314314            try:
    315315                r = tmpl.render(template.Context({}))
    316             except template.TemplateDoesNotExist, e:
     316            except template.TemplateDoesNotExist as e:
    317317                settings.TEMPLATE_DEBUG = old_td
    318318                self.assertEqual(e.args[0], 'missing.html')
    319319            self.assertEqual(r, None, 'Template rendering unexpectedly succeeded, produced: ->%r<-' % r)
    class Templates(unittest.TestCase):  
    340340            r = None
    341341            try:
    342342                r = tmpl.render(template.Context({}))
    343             except template.TemplateDoesNotExist, e:
     343            except template.TemplateDoesNotExist as e:
    344344                self.assertEqual(e.args[0], 'missing.html')
    345345            self.assertEqual(r, None, 'Template rendering unexpectedly succeeded, produced: ->%r<-' % r)
    346346
    class Templates(unittest.TestCase):  
    349349            tmpl = loader.get_template(load_name)
    350350            try:
    351351                tmpl.render(template.Context({}))
    352             except template.TemplateDoesNotExist, e:
     352            except template.TemplateDoesNotExist as e:
    353353                self.assertEqual(e.args[0], 'missing.html')
    354354            self.assertEqual(r, None, 'Template rendering unexpectedly succeeded, produced: ->%r<-' % r)
    355355        finally:
    class Templates(unittest.TestCase):  
    393393        from django.template import Template, TemplateSyntaxError
    394394        try:
    395395            t = Template("{% if 1 %}lala{% endblock %}{% endif %}")
    396         except TemplateSyntaxError, e:
     396        except TemplateSyntaxError as e:
    397397            self.assertEqual(e.args[0], "Invalid block tag: 'endblock', expected 'elif', 'else' or 'endif'")
    398398
    399399    def test_templates(self):
    class TemplateTagLoading(unittest.TestCase):  
    17141714        self.assertRaises(template.TemplateSyntaxError, template.Template, ttext)
    17151715        try:
    17161716            template.Template(ttext)
    1717         except template.TemplateSyntaxError, e:
     1717        except template.TemplateSyntaxError as e:
    17181718            self.assertTrue('ImportError' in e.args[0])
    17191719            self.assertTrue('Xtemplate' in e.args[0])
    17201720
    class TemplateTagLoading(unittest.TestCase):  
    17261726        self.assertRaises(template.TemplateSyntaxError, template.Template, ttext)
    17271727        try:
    17281728            template.Template(ttext)
    1729         except template.TemplateSyntaxError, e:
     1729        except template.TemplateSyntaxError as e:
    17301730            self.assertTrue('ImportError' in e.args[0])
    17311731            self.assertTrue('Xtemplate' in e.args[0])
    17321732
  • tests/regressiontests/test_client_regress/models.py

    diff --git a/tests/regressiontests/test_client_regress/models.py b/tests/regressiontests/test_client_regress/models.py
    index 0f98b2c..72ceff4 100644
    a b class AssertContainsTests(TestCase):  
    3939
    4040        try:
    4141            self.assertContains(response, 'text', status_code=999)
    42         except AssertionError, e:
     42        except AssertionError as e:
    4343            self.assertIn("Couldn't retrieve content: Response code was 200 (expected 999)", str(e))
    4444        try:
    4545            self.assertContains(response, 'text', status_code=999, msg_prefix='abc')
    46         except AssertionError, e:
     46        except AssertionError as e:
    4747            self.assertIn("abc: Couldn't retrieve content: Response code was 200 (expected 999)", str(e))
    4848
    4949        try:
    5050            self.assertNotContains(response, 'text', status_code=999)
    51         except AssertionError, e:
     51        except AssertionError as e:
    5252            self.assertIn("Couldn't retrieve content: Response code was 200 (expected 999)", str(e))
    5353        try:
    5454            self.assertNotContains(response, 'text', status_code=999, msg_prefix='abc')
    55         except AssertionError, e:
     55        except AssertionError as e:
    5656            self.assertIn("abc: Couldn't retrieve content: Response code was 200 (expected 999)", str(e))
    5757
    5858        try:
    5959            self.assertNotContains(response, 'once')
    60         except AssertionError, e:
     60        except AssertionError as e:
    6161            self.assertIn("Response should not contain 'once'", str(e))
    6262        try:
    6363            self.assertNotContains(response, 'once', msg_prefix='abc')
    64         except AssertionError, e:
     64        except AssertionError as e:
    6565            self.assertIn("abc: Response should not contain 'once'", str(e))
    6666
    6767        try:
    6868            self.assertContains(response, 'never', 1)
    69         except AssertionError, e:
     69        except AssertionError as e:
    7070            self.assertIn("Found 0 instances of 'never' in response (expected 1)", str(e))
    7171        try:
    7272            self.assertContains(response, 'never', 1, msg_prefix='abc')
    73         except AssertionError, e:
     73        except AssertionError as e:
    7474            self.assertIn("abc: Found 0 instances of 'never' in response (expected 1)", str(e))
    7575
    7676        try:
    7777            self.assertContains(response, 'once', 0)
    78         except AssertionError, e:
     78        except AssertionError as e:
    7979            self.assertIn("Found 1 instances of 'once' in response (expected 0)", str(e))
    8080        try:
    8181            self.assertContains(response, 'once', 0, msg_prefix='abc')
    82         except AssertionError, e:
     82        except AssertionError as e:
    8383            self.assertIn("abc: Found 1 instances of 'once' in response (expected 0)", str(e))
    8484
    8585        try:
    8686            self.assertContains(response, 'once', 2)
    87         except AssertionError, e:
     87        except AssertionError as e:
    8888            self.assertIn("Found 1 instances of 'once' in response (expected 2)", str(e))
    8989        try:
    9090            self.assertContains(response, 'once', 2, msg_prefix='abc')
    91         except AssertionError, e:
     91        except AssertionError as e:
    9292            self.assertIn("abc: Found 1 instances of 'once' in response (expected 2)", str(e))
    9393
    9494        try:
    9595            self.assertContains(response, 'twice', 1)
    96         except AssertionError, e:
     96        except AssertionError as e:
    9797            self.assertIn("Found 2 instances of 'twice' in response (expected 1)", str(e))
    9898        try:
    9999            self.assertContains(response, 'twice', 1, msg_prefix='abc')
    100         except AssertionError, e:
     100        except AssertionError as e:
    101101            self.assertIn("abc: Found 2 instances of 'twice' in response (expected 1)", str(e))
    102102
    103103        try:
    104104            self.assertContains(response, 'thrice')
    105         except AssertionError, e:
     105        except AssertionError as e:
    106106            self.assertIn("Couldn't find 'thrice' in response", str(e))
    107107        try:
    108108            self.assertContains(response, 'thrice', msg_prefix='abc')
    109         except AssertionError, e:
     109        except AssertionError as e:
    110110            self.assertIn("abc: Couldn't find 'thrice' in response", str(e))
    111111
    112112        try:
    113113            self.assertContains(response, 'thrice', 3)
    114         except AssertionError, e:
     114        except AssertionError as e:
    115115            self.assertIn("Found 0 instances of 'thrice' in response (expected 3)", str(e))
    116116        try:
    117117            self.assertContains(response, 'thrice', 3, msg_prefix='abc')
    118         except AssertionError, e:
     118        except AssertionError as e:
    119119            self.assertIn("abc: Found 0 instances of 'thrice' in response (expected 3)", str(e))
    120120
    121121    def test_unicode_contains(self):
    class AssertTemplateUsedTests(TestCase):  
    176176
    177177        try:
    178178            self.assertTemplateUsed(response, 'GET Template')
    179         except AssertionError, e:
     179        except AssertionError as e:
    180180            self.assertIn("No templates used to render the response", str(e))
    181181
    182182        try:
    183183            self.assertTemplateUsed(response, 'GET Template', msg_prefix='abc')
    184         except AssertionError, e:
     184        except AssertionError as e:
    185185            self.assertIn("abc: No templates used to render the response", str(e))
    186186
    187187    def test_single_context(self):
    class AssertTemplateUsedTests(TestCase):  
    190190
    191191        try:
    192192            self.assertTemplateNotUsed(response, 'Empty GET Template')
    193         except AssertionError, e:
     193        except AssertionError as e:
    194194            self.assertIn("Template 'Empty GET Template' was used unexpectedly in rendering the response", str(e))
    195195
    196196        try:
    197197            self.assertTemplateNotUsed(response, 'Empty GET Template', msg_prefix='abc')
    198         except AssertionError, e:
     198        except AssertionError as e:
    199199            self.assertIn("abc: Template 'Empty GET Template' was used unexpectedly in rendering the response", str(e))
    200200
    201201        try:
    202202            self.assertTemplateUsed(response, 'Empty POST Template')
    203         except AssertionError, e:
     203        except AssertionError as e:
    204204            self.assertIn("Template 'Empty POST Template' was not a template used to render the response. Actual template(s) used: Empty GET Template", str(e))
    205205
    206206        try:
    207207            self.assertTemplateUsed(response, 'Empty POST Template', msg_prefix='abc')
    208         except AssertionError, e:
     208        except AssertionError as e:
    209209            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))
    210210
    211211    def test_multiple_context(self):
    class AssertTemplateUsedTests(TestCase):  
    221221        self.assertContains(response, 'POST data OK')
    222222        try:
    223223            self.assertTemplateNotUsed(response, "form_view.html")
    224         except AssertionError, e:
     224        except AssertionError as e:
    225225            self.assertIn("Template 'form_view.html' was used unexpectedly in rendering the response", str(e))
    226226
    227227        try:
    228228            self.assertTemplateNotUsed(response, 'base.html')
    229         except AssertionError, e:
     229        except AssertionError as e:
    230230            self.assertIn("Template 'base.html' was used unexpectedly in rendering the response", str(e))
    231231
    232232        try:
    233233            self.assertTemplateUsed(response, "Valid POST Template")
    234         except AssertionError, e:
     234        except AssertionError as e:
    235235            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))
    236236
    237237class AssertRedirectsTests(TestCase):
    class AssertRedirectsTests(TestCase):  
    241241        response = self.client.get('/test_client/permanent_redirect_view/')
    242242        try:
    243243            self.assertRedirects(response, '/test_client/get_view/')
    244         except AssertionError, e:
     244        except AssertionError as e:
    245245            self.assertIn("Response didn't redirect as expected: Response code was 301 (expected 302)", str(e))
    246246
    247247        try:
    248248            self.assertRedirects(response, '/test_client/get_view/', msg_prefix='abc')
    249         except AssertionError, e:
     249        except AssertionError as e:
    250250            self.assertIn("abc: Response didn't redirect as expected: Response code was 301 (expected 302)", str(e))
    251251
    252252    def test_lost_query(self):
    class AssertRedirectsTests(TestCase):  
    254254        response = self.client.get('/test_client/redirect_view/', {'var': 'value'})
    255255        try:
    256256            self.assertRedirects(response, '/test_client/get_view/')
    257         except AssertionError, e:
     257        except AssertionError as e:
    258258            self.assertIn("Response redirected to 'http://testserver/test_client/get_view/?var=value', expected 'http://testserver/test_client/get_view/'", str(e))
    259259
    260260        try:
    261261            self.assertRedirects(response, '/test_client/get_view/', msg_prefix='abc')
    262         except AssertionError, e:
     262        except AssertionError as e:
    263263            self.assertIn("abc: Response redirected to 'http://testserver/test_client/get_view/?var=value', expected 'http://testserver/test_client/get_view/'", str(e))
    264264
    265265    def test_incorrect_target(self):
    class AssertRedirectsTests(TestCase):  
    268268        try:
    269269            # Should redirect to get_view
    270270            self.assertRedirects(response, '/test_client/some_view/')
    271         except AssertionError, e:
     271        except AssertionError as e:
    272272            self.assertIn("Response didn't redirect as expected: Response code was 301 (expected 302)", str(e))
    273273
    274274    def test_target_page(self):
    class AssertRedirectsTests(TestCase):  
    277277        try:
    278278            # The redirect target responds with a 301 code, not 200
    279279            self.assertRedirects(response, 'http://testserver/test_client/permanent_redirect_view/')
    280         except AssertionError, e:
     280        except AssertionError as e:
    281281            self.assertIn("Couldn't retrieve redirection page '/test_client/permanent_redirect_view/': response code was 301 (expected 200)", str(e))
    282282
    283283        try:
    284284            # The redirect target responds with a 301 code, not 200
    285285            self.assertRedirects(response, 'http://testserver/test_client/permanent_redirect_view/', msg_prefix='abc')
    286         except AssertionError, e:
     286        except AssertionError as e:
    287287            self.assertIn("abc: Couldn't retrieve redirection page '/test_client/permanent_redirect_view/': response code was 301 (expected 200)", str(e))
    288288
    289289    def test_redirect_chain(self):
    class AssertRedirectsTests(TestCase):  
    386386        response = self.client.get('/test_client/get_view/', follow=True)
    387387        try:
    388388            self.assertRedirects(response, '/test_client/get_view/')
    389         except AssertionError, e:
     389        except AssertionError as e:
    390390            self.assertIn("Response didn't redirect as expected: Response code was 200 (expected 302)", str(e))
    391391
    392392        try:
    393393            self.assertRedirects(response, '/test_client/get_view/', msg_prefix='abc')
    394         except AssertionError, e:
     394        except AssertionError as e:
    395395            self.assertIn("abc: Response didn't redirect as expected: Response code was 200 (expected 302)", str(e))
    396396
    397397    def test_redirect_on_non_redirect_page(self):
    class AssertRedirectsTests(TestCase):  
    400400        response = self.client.get('/test_client/get_view/')
    401401        try:
    402402            self.assertRedirects(response, '/test_client/get_view/')
    403         except AssertionError, e:
     403        except AssertionError as e:
    404404            self.assertIn("Response didn't redirect as expected: Response code was 200 (expected 302)", str(e))
    405405
    406406        try:
    407407            self.assertRedirects(response, '/test_client/get_view/', msg_prefix='abc')
    408         except AssertionError, e:
     408        except AssertionError as e:
    409409            self.assertIn("abc: Response didn't redirect as expected: Response code was 200 (expected 302)", str(e))
    410410
    411411
    class AssertFormErrorTests(TestCase):  
    425425
    426426        try:
    427427            self.assertFormError(response, 'wrong_form', 'some_field', 'Some error.')
    428         except AssertionError, e:
     428        except AssertionError as e:
    429429            self.assertIn("The form 'wrong_form' was not used to render the response", str(e))
    430430        try:
    431431            self.assertFormError(response, 'wrong_form', 'some_field', 'Some error.', msg_prefix='abc')
    432         except AssertionError, e:
     432        except AssertionError as e:
    433433            self.assertIn("abc: The form 'wrong_form' was not used to render the response", str(e))
    434434
    435435    def test_unknown_field(self):
    class AssertFormErrorTests(TestCase):  
    447447
    448448        try:
    449449            self.assertFormError(response, 'form', 'some_field', 'Some error.')
    450         except AssertionError, e:
     450        except AssertionError as e:
    451451            self.assertIn("The form 'form' in context 0 does not contain the field 'some_field'", str(e))
    452452        try:
    453453            self.assertFormError(response, 'form', 'some_field', 'Some error.', msg_prefix='abc')
    454         except AssertionError, e:
     454        except AssertionError as e:
    455455            self.assertIn("abc: The form 'form' in context 0 does not contain the field 'some_field'", str(e))
    456456
    457457    def test_noerror_field(self):
    class AssertFormErrorTests(TestCase):  
    469469
    470470        try:
    471471            self.assertFormError(response, 'form', 'value', 'Some error.')
    472         except AssertionError, e:
     472        except AssertionError as e:
    473473            self.assertIn("The field 'value' on form 'form' in context 0 contains no errors", str(e))
    474474        try:
    475475            self.assertFormError(response, 'form', 'value', 'Some error.', msg_prefix='abc')
    476         except AssertionError, e:
     476        except AssertionError as e:
    477477            self.assertIn("abc: The field 'value' on form 'form' in context 0 contains no errors", str(e))
    478478
    479479    def test_unknown_error(self):
    class AssertFormErrorTests(TestCase):  
    491491
    492492        try:
    493493            self.assertFormError(response, 'form', 'email', 'Some error.')
    494         except AssertionError, e:
     494        except AssertionError as e:
    495495            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))
    496496        try:
    497497            self.assertFormError(response, 'form', 'email', 'Some error.', msg_prefix='abc')
    498         except AssertionError, e:
     498        except AssertionError as e:
    499499            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))
    500500
    501501    def test_unknown_nonfield_error(self):
    class AssertFormErrorTests(TestCase):  
    516516
    517517        try:
    518518            self.assertFormError(response, 'form', None, 'Some error.')
    519         except AssertionError, e:
     519        except AssertionError as e:
    520520            self.assertIn("The form 'form' in context 0 does not contain the non-field error 'Some error.' (actual errors: )", str(e))
    521521        try:
    522522            self.assertFormError(response, 'form', None, 'Some error.', msg_prefix='abc')
    523         except AssertionError, e:
     523        except AssertionError as e:
    524524            self.assertIn("abc: The form 'form' in context 0 does not contain the non-field error 'Some error.' (actual errors: )", str(e))
    525525
    526526class LoginTests(TestCase):
    class ContextTests(TestCase):  
    677677        try:
    678678            response.context['does-not-exist']
    679679            self.fail('Should not be able to retrieve non-existent key')
    680         except KeyError, e:
     680        except KeyError as e:
    681681            self.assertEqual(e.args[0], 'does-not-exist')
    682682
    683683    def test_inherited_context(self):
    class ContextTests(TestCase):  
    693693        try:
    694694            response.context['does-not-exist']
    695695            self.fail('Should not be able to retrieve non-existent key')
    696         except KeyError, e:
     696        except KeyError as e:
    697697            self.assertEqual(e.args[0], 'does-not-exist')
    698698
    699699    def test_15368(self):
  • tests/regressiontests/urlpatterns_reverse/tests.py

    diff --git a/tests/regressiontests/urlpatterns_reverse/tests.py b/tests/regressiontests/urlpatterns_reverse/tests.py
    index a1c9244..d25235e 100644
    a b class URLPatternReverse(TestCase):  
    161161        for name, expected, args, kwargs in test_data:
    162162            try:
    163163                got = reverse(name, args=args, kwargs=kwargs)
    164             except NoReverseMatch, e:
     164            except NoReverseMatch as e:
    165165                self.assertEqual(expected, NoReverseMatch)
    166166            else:
    167167                self.assertEqual(got, expected)
    class ResolverTests(unittest.TestCase):  
    207207        try:
    208208            resolve('/included/non-existent-url', urlconf=urls)
    209209            self.fail('resolve did not raise a 404')
    210         except Resolver404, e:
     210        except Resolver404 as e:
    211211            # make sure we at least matched the root ('/') url resolver:
    212212            self.assertTrue('tried' in e.args[0])
    213213            tried = e.args[0]['tried']
Back to Top