Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Fixed #18013 -- Use the new 'as' syntax for exceptions.

Thanks Clueless for the initial patch.
Note that unittest has been purposely left out (external package only used by Python 2.6).
  • Loading branch information...
commit 3904b74a3f2f92fefe1d39281ed683c52f2fef03 1 parent eefb00f
@claudep claudep authored
Showing with 306 additions and 354 deletions.
  1. +1 −1  django/conf/__init__.py
  2. +1 −1  django/contrib/admin/tests.py
  3. +1 −1  django/contrib/admin/util.py
  4. +2 −2 django/contrib/admin/views/main.py
  5. +1 −1  django/contrib/admindocs/views.py
  6. +2 −2 django/contrib/auth/__init__.py
  7. +1 −1  django/contrib/comments/views/comments.py
  8. +1 −1  django/contrib/formtools/wizard/storage/__init__.py
  9. +2 −2 django/contrib/gis/db/backends/base.py
  10. +1 −1  django/contrib/gis/db/backends/oracle/introspection.py
  11. +1 −3 django/contrib/gis/db/backends/postgis/operations.py
  12. +1 −1  django/contrib/gis/db/backends/spatialite/base.py
  13. +1 −1  django/contrib/gis/db/backends/spatialite/operations.py
  14. +2 −2 django/contrib/gis/geometry/backend/__init__.py
  15. +1 −1  django/contrib/gis/management/commands/ogrinspect.py
  16. +15 −60 django/contrib/gis/tests/test_measure.py
  17. +3 −3 django/contrib/gis/utils/layermapping.py
  18. +1 −1  django/contrib/markup/tests.py
  19. +1 −1  django/contrib/messages/storage/__init__.py
  20. +1 −1  django/contrib/sessions/backends/file.py
  21. +1 −1  django/contrib/staticfiles/finders.py
  22. +1 −1  django/contrib/staticfiles/handlers.py
  23. +1 −1  django/core/cache/__init__.py
  24. +1 −1  django/core/files/move.py
  25. +4 −4 django/core/files/storage.py
  26. +1 −1  django/core/files/uploadedfile.py
  27. +4 −3 django/core/files/uploadhandler.py
  28. +3 −3 django/core/handlers/base.py
  29. +1 −1  django/core/mail/__init__.py
  30. +1 −1  django/core/mail/backends/filebased.py
  31. +1 −1  django/core/management/__init__.py
  32. +3 −3 django/core/management/base.py
  33. +1 −1  django/core/management/commands/createcachetable.py
  34. +1 −1  django/core/management/commands/dumpdata.py
  35. +1 −1  django/core/management/commands/flush.py
  36. +1 −1  django/core/management/commands/loaddata.py
  37. +1 −1  django/core/management/commands/runserver.py
  38. +3 −3 django/core/management/commands/syncdb.py
  39. +3 −3 django/core/management/templates.py
  40. +1 −1  django/core/serializers/json.py
  41. +1 −1  django/core/serializers/pyyaml.py
  42. +3 −3 django/core/servers/basehttp.py
  43. +1 −1  django/core/servers/fastcgi.py
  44. +2 −2 django/core/signing.py
  45. +3 −3 django/core/urlresolvers.py
  46. +2 −2 django/core/validators.py
  47. +2 −2 django/db/backends/creation.py
  48. +7 −7 django/db/backends/mysql/base.py
  49. +8 −8 django/db/backends/oracle/base.py
  50. +5 −5 django/db/backends/oracle/creation.py
  51. +6 −6 django/db/backends/postgresql_psycopg2/base.py
  52. +6 −6 django/db/backends/sqlite3/base.py
  53. +1 −1  django/db/backends/sqlite3/creation.py
  54. +4 −4 django/db/models/base.py
  55. +1 −1  django/db/models/fields/__init__.py
  56. +2 −2 django/db/models/query.py
  57. +1 −1  django/db/models/sql/query.py
  58. +2 −2 django/db/utils.py
  59. +1 −1  django/dispatch/dispatcher.py
  60. +2 −2 django/dispatch/saferef.py
  61. +2 −2 django/forms/fields.py
  62. +2 −2 django/forms/forms.py
  63. +1 −1  django/forms/formsets.py
  64. +3 −3 django/forms/models.py
  65. +1 −1  django/forms/util.py
  66. +2 −2 django/http/__init__.py
  67. +3 −3 django/http/multipartparser.py
  68. +3 −3 django/template/base.py
  69. +1 −1  django/template/context.py
  70. +2 −2 django/template/debug.py
  71. +1 −1  django/template/defaultfilters.py
  72. +5 −5 django/template/defaulttags.py
  73. +3 −3 django/template/loader.py
  74. +1 −1  django/template/loaders/app_directories.py
  75. +4 −4 django/test/_doctest.py
  76. +1 −1  django/test/client.py
  77. +3 −3 django/test/testcases.py
  78. +2 −2 django/utils/daemonize.py
  79. +1 −1  django/utils/decorators.py
  80. +14 −14 django/utils/dictconfig.py
  81. +1 −1  django/utils/encoding.py
  82. +1 −1  django/views/debug.py
  83. +2 −2 docs/ref/models/instances.txt
  84. +1 −1  extras/csrf_migration_helper.py
  85. +5 −5 tests/modeltests/basic/tests.py
  86. +1 −1  tests/modeltests/get_or_create/tests.py
  87. +1 −1  tests/modeltests/invalid_models/tests.py
  88. +2 −2 tests/modeltests/lookup/tests.py
  89. +2 −4 tests/modeltests/select_for_update/tests.py
  90. +1 −1  tests/modeltests/validation/models.py
  91. +16 −16 tests/modeltests/validation/test_error_messages.py
  92. +3 −3 tests/modeltests/validation/test_unique.py
  93. +1 −1  tests/regressiontests/app_loading/tests.py
  94. +3 −3 tests/regressiontests/backends/tests.py
  95. +6 −6 tests/regressiontests/file_uploads/tests.py
  96. +1 −1  tests/regressiontests/forms/tests/error_messages.py
  97. +1 −1  tests/regressiontests/forms/tests/validators.py
  98. +2 −2 tests/regressiontests/middleware/tests.py
  99. +2 −2 tests/regressiontests/middleware_exceptions/tests.py
  100. +1 −1  tests/regressiontests/model_fields/tests.py
  101. +1 −1  tests/regressiontests/model_forms_regress/tests.py
  102. +1 −1  tests/regressiontests/servers/tests.py
  103. +1 −1  tests/regressiontests/settings_tests/tests.py
  104. +1 −1  tests/regressiontests/templates/nodelist.py
  105. +8 −8 tests/regressiontests/templates/tests.py
  106. +50 −50 tests/regressiontests/test_client_regress/models.py
  107. +2 −2 tests/regressiontests/urlpatterns_reverse/tests.py
View
2  django/conf/__init__.py
@@ -91,7 +91,7 @@ def __init__(self, settings_module):
try:
mod = importlib.import_module(self.SETTINGS_MODULE)
- except ImportError, e:
+ except ImportError as e:
raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))
# Settings that should be converted into tuples if they're mistakenly entered
View
2  django/contrib/admin/tests.py
@@ -14,7 +14,7 @@ def setUpClass(cls):
mod = import_module(module)
WebDriver = getattr(mod, attr)
cls.selenium = WebDriver()
- except Exception, e:
+ except Exception as e:
raise SkipTest('Selenium webdriver "%s" not installed or not '
'operational: %s' % (cls.webdriver_class, str(e)))
super(AdminSeleniumWebDriverTestCase, cls).setUpClass()
View
2  django/contrib/admin/util.py
@@ -156,7 +156,7 @@ def collect(self, objs, source_attr=None, **kwargs):
self.add_edge(None, obj)
try:
return super(NestedObjects, self).collect(objs, source_attr=source_attr, **kwargs)
- except models.ProtectedError, e:
+ except models.ProtectedError as e:
self.protected.update(e.protected_objects)
def related_objects(self, related, objs):
View
4 django/contrib/admin/views/main.py
@@ -139,7 +139,7 @@ def get_filters(self, request):
use_distinct = (use_distinct or
lookup_needs_distinct(self.lookup_opts, key))
return filter_specs, bool(filter_specs), lookup_params, use_distinct
- except FieldDoesNotExist, e:
+ except FieldDoesNotExist as e:
raise IncorrectLookupParameters(e)
def get_query_string(self, new_params=None, remove=None):
@@ -316,7 +316,7 @@ def get_query_set(self, request):
# Allow certain types of errors to be re-raised as-is so that the
# caller can treat them in a special way.
raise
- except Exception, e:
+ except Exception as e:
# Every other error is caught with a naked except, because we don't
# have any other way of validating lookup parameters. They might be
# invalid if the keyword arguments are incorrect, or if the values
View
2  django/contrib/admindocs/views.py
@@ -318,7 +318,7 @@ def load_all_installed_template_libraries():
for library_name in libraries:
try:
lib = template.get_library(library_name)
- except template.InvalidTemplateLibrary, e:
+ except template.InvalidTemplateLibrary:
pass
def get_return_data_type(func_name):
View
4 django/contrib/auth/__init__.py
@@ -11,9 +11,9 @@ def load_backend(path):
module, attr = path[:i], path[i+1:]
try:
mod = import_module(module)
- except ImportError, e:
+ except ImportError as e:
raise ImproperlyConfigured('Error importing authentication backend %s: "%s"' % (path, e))
- except ValueError, e:
+ except ValueError:
raise ImproperlyConfigured('Error importing authentication backends. Is AUTHENTICATION_BACKENDS a correctly defined list or tuple?')
try:
cls = getattr(mod, attr)
View
2  django/contrib/comments/views/comments.py
@@ -66,7 +66,7 @@ def post_comment(request, next=None, using=None):
return CommentPostBadRequest(
"No object matching content-type %r and object PK %r exists." % \
(escape(ctype), escape(object_pk)))
- except (ValueError, ValidationError), e:
+ except (ValueError, ValidationError) as e:
return CommentPostBadRequest(
"Attempting go get content-type %r and object PK %r exists raised %s" % \
(escape(ctype), escape(object_pk), e.__class__.__name__))
View
2  django/contrib/formtools/wizard/storage/__init__.py
@@ -10,7 +10,7 @@ def get_storage(path, *args, **kwargs):
module, attr = path[:i], path[i+1:]
try:
mod = import_module(module)
- except ImportError, e:
+ except ImportError as e:
raise MissingStorageModule(
'Error loading storage %s: "%s"' % (module, e))
try:
View
4 django/contrib/gis/db/backends/base.py
@@ -164,13 +164,13 @@ def srs(self):
try:
self._srs = gdal.SpatialReference(self.wkt)
return self.srs
- except Exception, msg:
+ except Exception as msg:
pass
try:
self._srs = gdal.SpatialReference(self.proj4text)
return self.srs
- except Exception, msg:
+ except Exception as msg:
pass
raise Exception('Could not get OSR SpatialReference from WKT: %s\nError:\n%s' % (self.wkt, msg))
View
2  django/contrib/gis/db/backends/oracle/introspection.py
@@ -16,7 +16,7 @@ def get_geometry_type(self, table_name, geo_col):
cursor.execute('SELECT "DIMINFO", "SRID" FROM "USER_SDO_GEOM_METADATA" WHERE "TABLE_NAME"=%s AND "COLUMN_NAME"=%s',
(table_name.upper(), geo_col.upper()))
row = cursor.fetchone()
- except Exception, msg:
+ except Exception as msg:
raise Exception('Could not find entry in USER_SDO_GEOM_METADATA corresponding to "%s"."%s"\n'
'Error message: %s.' % (table_name, geo_col, msg))
View
4 django/contrib/gis/db/backends/postgis/operations.py
@@ -107,9 +107,7 @@ def __init__(self, connection):
'Was the database created from a spatial database '
'template?' % self.connection.settings_dict['NAME']
)
- except Exception, e:
- # TODO: Raise helpful exceptions as they become known.
- raise
+ # TODO: Raise helpful exceptions as they become known.
# PostGIS-specific operators. The commented descriptions of these
# operators come from Section 7.6 of the PostGIS 1.4 documentation.
View
2  django/contrib/gis/db/backends/spatialite/base.py
@@ -56,7 +56,7 @@ def _cursor(self):
cur = self.connection.cursor(factory=SQLiteCursorWrapper)
try:
cur.execute("SELECT load_extension(%s)", (self.spatialite_lib,))
- except Exception, msg:
+ except Exception as msg:
raise ImproperlyConfigured('Unable to load the SpatiaLite library extension '
'"%s" because: %s' % (self.spatialite_lib, msg))
return cur
View
2  django/contrib/gis/db/backends/spatialite/operations.py
@@ -122,7 +122,7 @@ def __init__(self, connection):
self.spatial_version = version
except ImproperlyConfigured:
raise
- except Exception, msg:
+ except Exception as msg:
raise ImproperlyConfigured('Cannot determine the SpatiaLite version for the "%s" '
'database (error was "%s"). Was the SpatiaLite initialization '
'SQL loaded on this database?' %
View
4 django/contrib/gis/geometry/backend/__init__.py
@@ -6,10 +6,10 @@
try:
module = import_module('.%s' % geom_backend, 'django.contrib.gis.geometry.backend')
-except ImportError, e:
+except ImportError:
try:
module = import_module(geom_backend)
- except ImportError, e_user:
+ except ImportError:
raise ImproperlyConfigured('Could not import user-defined GEOMETRY_BACKEND '
'"%s".' % geom_backend)
View
2  django/contrib/gis/management/commands/ogrinspect.py
@@ -87,7 +87,7 @@ def handle(self, *args, **options):
# Getting the OGR DataSource from the string parameter.
try:
ds = gdal.DataSource(data_source)
- except gdal.OGRException, msg:
+ except gdal.OGRException as msg:
raise CommandError(msg)
# Whether the user wants to generate the LayerMapping dictionary as well.
View
75 django/contrib/gis/tests/test_measure.py
@@ -62,32 +62,20 @@ def testAddition(self):
d4 -= d1
self.assertEqual(d4.m, -200)
- try:
+ with self.assertRaises(TypeError):
d5 = d1 + 1
- except TypeError, e:
- pass
- else:
self.fail('Distance + number should raise TypeError')
- try:
+ with self.assertRaises(TypeError):
d5 = d1 - 1
- except TypeError, e:
- pass
- else:
self.fail('Distance - number should raise TypeError')
- try:
+ with self.assertRaises(TypeError):
d1 += 1
- except TypeError, e:
- pass
- else:
self.fail('Distance += number should raise TypeError')
- try:
+ with self.assertRaises(TypeError):
d1 -= 1
- except TypeError, e:
- pass
- else:
self.fail('Distance -= number should raise TypeError')
def testMultiplication(self):
@@ -110,25 +98,16 @@ def testMultiplication(self):
self.assertTrue(isinstance(a5, Area))
self.assertEqual(a5.sq_m, 100*10)
- try:
+ with self.assertRaises(TypeError):
d1 *= D(m=1)
- except TypeError, e:
- pass
- else:
self.fail('Distance *= Distance should raise TypeError')
- try:
+ with self.assertRaises(TypeError):
d5 = d1 / D(m=1)
- except TypeError, e:
- pass
- else:
self.fail('Distance / Distance should raise TypeError')
- try:
+ with self.assertRaises(TypeError):
d1 /= D(m=1)
- except TypeError, e:
- pass
- else:
self.fail('Distance /= Distance should raise TypeError')
def testUnitConversions(self):
@@ -217,32 +196,20 @@ def testAddition(self):
a4 -= a1
self.assertEqual(a4.sq_m, -200)
- try:
+ with self.assertRaises(TypeError):
a5 = a1 + 1
- except TypeError, e:
- pass
- else:
self.fail('Area + number should raise TypeError')
- try:
+ with self.assertRaises(TypeError):
a5 = a1 - 1
- except TypeError, e:
- pass
- else:
self.fail('Area - number should raise TypeError')
- try:
+ with self.assertRaises(TypeError):
a1 += 1
- except TypeError, e:
- pass
- else:
self.fail('Area += number should raise TypeError')
- try:
+ with self.assertRaises(TypeError):
a1 -= 1
- except TypeError, e:
- pass
- else:
self.fail('Area -= number should raise TypeError')
def testMultiplication(self):
@@ -261,32 +228,20 @@ def testMultiplication(self):
a4 /= 5
self.assertEqual(a4.sq_m, 10)
- try:
+ with self.assertRaises(TypeError):
a5 = a1 * A(sq_m=1)
- except TypeError, e:
- pass
- else:
self.fail('Area * Area should raise TypeError')
- try:
+ with self.assertRaises(TypeError):
a1 *= A(sq_m=1)
- except TypeError, e:
- pass
- else:
self.fail('Area *= Area should raise TypeError')
- try:
+ with self.assertRaises(TypeError):
a5 = a1 / A(sq_m=1)
- except TypeError, e:
- pass
- else:
self.fail('Area / Area should raise TypeError')
- try:
+ with self.assertRaises(TypeError):
a1 /= A(sq_m=1)
- except TypeError, e:
- pass
- else:
self.fail('Area /= Area should raise TypeError')
def testUnitConversions(self):
View
6 django/contrib/gis/utils/layermapping.py
@@ -430,7 +430,7 @@ def coord_transform(self):
# Creating the CoordTransform object
return CoordTransform(self.source_srs, target_srs)
- except Exception, msg:
+ except Exception as msg:
raise LayerMapError('Could not translate between the data source and model geometry: %s' % msg)
def geometry_field(self):
@@ -514,7 +514,7 @@ def _save(feat_range=default_range, num_feat=0, num_saved=0):
# Getting the keyword arguments
try:
kwargs = self.feature_kwargs(feat)
- except LayerMapError, msg:
+ except LayerMapError as msg:
# Something borked the validation
if strict: raise
elif not silent:
@@ -553,7 +553,7 @@ def _save(feat_range=default_range, num_feat=0, num_saved=0):
if verbose: stream.write('%s: %s\n' % (is_update and 'Updated' or 'Saved', m))
except SystemExit:
raise
- except Exception, msg:
+ except Exception as msg:
if self.transaction_mode == 'autocommit':
# Rolling back the transaction so that other model saves
# will work.
View
2  django/contrib/markup/tests.py
@@ -87,7 +87,7 @@ def test_docutils(self):
# Docutils v0.4 and earlier
self.assertEqual(rendered, """<p>Paragraph 1</p>
<p>Paragraph 2 with a <a class="reference" href="http://www.example.com/">link</a></p>""")
- except AssertionError, e:
+ except AssertionError:
# Docutils from SVN (which will become 0.5)
self.assertEqual(rendered, """<p>Paragraph 1</p>
<p>Paragraph 2 with a <a class="reference external" href="http://www.example.com/">link</a></p>""")
View
2  django/contrib/messages/storage/__init__.py
@@ -15,7 +15,7 @@ def get_storage(import_path):
module, classname = import_path[:dot], import_path[dot + 1:]
try:
mod = import_module(module)
- except ImportError, e:
+ except ImportError as e:
raise ImproperlyConfigured('Error importing module %s: "%s"' %
(module, e))
try:
View
2  django/contrib/sessions/backends/file.py
@@ -90,7 +90,7 @@ def save(self, must_create=False):
fd = os.open(session_file_name, flags)
os.close(fd)
- except OSError, e:
+ except OSError as e:
if must_create and e.errno == errno.EEXIST:
raise CreateError
raise
View
2  django/contrib/staticfiles/finders.py
@@ -260,7 +260,7 @@ def _get_finder(import_path):
module, attr = import_path.rsplit('.', 1)
try:
mod = import_module(module)
- except ImportError, e:
+ except ImportError as e:
raise ImproperlyConfigured('Error importing module %s: "%s"' %
(module, e))
try:
View
2  django/contrib/staticfiles/handlers.py
@@ -56,7 +56,7 @@ def get_response(self, request):
if self._should_handle(request.path):
try:
return self.serve(request)
- except Http404, e:
+ except Http404 as e:
if settings.DEBUG:
from django.views import debug
return debug.technical_404_response(request, e)
View
2  django/core/cache/__init__.py
@@ -128,7 +128,7 @@ def get_cache(backend, **kwargs):
mod_path, cls_name = backend.rsplit('.', 1)
mod = importlib.import_module(mod_path)
backend_cls = getattr(mod, cls_name)
- except (AttributeError, ImportError), e:
+ except (AttributeError, ImportError) as e:
raise InvalidCacheBackendError(
"Could not find backend '%s': %s" % (backend, e))
cache = backend_cls(location, params)
View
2  django/core/files/move.py
@@ -79,7 +79,7 @@ def file_move_safe(old_file_name, new_file_name, chunk_size = 1024*64, allow_ove
try:
os.remove(old_file_name)
- except OSError, e:
+ except OSError as e:
# Certain operating systems (Cygwin and Windows)
# fail when deleting opened files, ignore it. (For the
# systems where this happens, temporary files will be auto-deleted
View
8 django/core/files/storage.py
@@ -166,7 +166,7 @@ def _save(self, name, content):
if not os.path.exists(directory):
try:
os.makedirs(directory)
- except OSError, e:
+ except OSError as e:
if e.errno != errno.EEXIST:
raise
if not os.path.isdir(directory):
@@ -197,7 +197,7 @@ def _save(self, name, content):
finally:
locks.unlock(fd)
os.close(fd)
- except OSError, e:
+ except OSError as e:
if e.errno == errno.EEXIST:
# Ooops, the file exists. We need a new file name.
name = self.get_available_name(name)
@@ -222,7 +222,7 @@ def delete(self, name):
if os.path.exists(name):
try:
os.remove(name)
- except OSError, e:
+ except OSError as e:
if e.errno != errno.ENOENT:
raise
@@ -273,7 +273,7 @@ def get_storage_class(import_path=None):
module, classname = import_path[:dot], import_path[dot+1:]
try:
mod = import_module(module)
- except ImportError, e:
+ except ImportError as e:
raise ImproperlyConfigured('Error importing storage module %s: "%s"' % (module, e))
try:
return getattr(mod, classname)
View
2  django/core/files/uploadedfile.py
@@ -75,7 +75,7 @@ def temporary_file_path(self):
def close(self):
try:
return self.file.close()
- except OSError, e:
+ except OSError as e:
if e.errno != 2:
# Means the file was moved or deleted before the tempfile
# could unlink it. Still sets self.file.close_called and
View
7 django/core/files/uploadhandler.py
@@ -204,10 +204,11 @@ def load_handler(path, *args, **kwargs):
module, attr = path[:i], path[i+1:]
try:
mod = importlib.import_module(module)
- except ImportError, e:
+ except ImportError as e:
raise ImproperlyConfigured('Error importing upload handler module %s: "%s"' % (module, e))
- except ValueError, e:
- raise ImproperlyConfigured('Error importing upload handler module. Is FILE_UPLOAD_HANDLERS a correctly defined list or tuple?')
+ except ValueError:
+ raise ImproperlyConfigured('Error importing upload handler module.'
+ 'Is FILE_UPLOAD_HANDLERS a correctly defined list or tuple?')
try:
cls = getattr(mod, attr)
except AttributeError:
View
6 django/core/handlers/base.py
@@ -43,7 +43,7 @@ def load_middleware(self):
raise exceptions.ImproperlyConfigured('%s isn\'t a middleware module' % middleware_path)
try:
mod = import_module(mw_module)
- except ImportError, e:
+ except ImportError as e:
raise exceptions.ImproperlyConfigured('Error importing middleware %s: "%s"' % (mw_module, e))
try:
mw_class = getattr(mod, mw_classname)
@@ -109,7 +109,7 @@ def get_response(self, request):
if response is None:
try:
response = callback(request, *callback_args, **callback_kwargs)
- except Exception, e:
+ except Exception as e:
# If the view raised an exception, run it through exception
# middleware, and if the exception middleware returns a
# response, use that. Otherwise, reraise the exception.
@@ -135,7 +135,7 @@ def get_response(self, request):
response = middleware_method(request, response)
response = response.render()
- except http.Http404, e:
+ except http.Http404 as e:
logger.warning('Not Found: %s', request.path,
extra={
'status_code': 404,
View
2  django/core/mail/__init__.py
@@ -30,7 +30,7 @@ def get_connection(backend=None, fail_silently=False, **kwds):
try:
mod_name, klass_name = path.rsplit('.', 1)
mod = import_module(mod_name)
- except ImportError, e:
+ except ImportError as e:
raise ImproperlyConfigured(('Error importing email backend module %s: "%s"'
% (mod_name, e)))
try:
View
2  django/core/mail/backends/filebased.py
@@ -25,7 +25,7 @@ def __init__(self, *args, **kwargs):
elif not os.path.exists(self.file_path):
try:
os.makedirs(self.file_path)
- except OSError, err:
+ except OSError as err:
raise ImproperlyConfigured('Could not create directory for saving email messages: %s (%s)' % (self.file_path, err))
# Make sure that self.file_path is writable.
if not os.access(self.file_path, os.W_OK):
View
2  django/core/management/__init__.py
@@ -51,7 +51,7 @@ def find_management_module(app_name):
# of the app_name but the project directory itself isn't on the path.
try:
f, path, descr = imp.find_module(part,path)
- except ImportError,e:
+ except ImportError as e:
if os.path.basename(os.getcwd()) != part:
raise e
View
6 django/core/management/base.py
@@ -214,7 +214,7 @@ def execute(self, *args, **options):
from django.utils import translation
saved_lang = translation.get_language()
translation.activate('en-us')
- except ImportError, e:
+ except ImportError as e:
# If settings should be available, but aren't,
# raise the error and quit.
if show_traceback:
@@ -240,7 +240,7 @@ def execute(self, *args, **options):
self.stdout.write(output)
if self.output_transaction:
self.stdout.write('\n' + self.style.SQL_KEYWORD("COMMIT;") + '\n')
- except CommandError, e:
+ except CommandError as e:
if show_traceback:
traceback.print_exc()
else:
@@ -297,7 +297,7 @@ def handle(self, *app_labels, **options):
raise CommandError('Enter at least one appname.')
try:
app_list = [models.get_app(app_label) for app_label in app_labels]
- except (ImproperlyConfigured, ImportError), e:
+ except (ImproperlyConfigured, ImportError) as e:
raise CommandError("%s. Are you sure your INSTALLED_APPS setting is correct?" % e)
output = []
for app in app_list:
View
2  django/core/management/commands/createcachetable.py
@@ -54,7 +54,7 @@ def handle_label(self, tablename, **options):
curs = connection.cursor()
try:
curs.execute("\n".join(full_statement))
- except DatabaseError, e:
+ except DatabaseError as e:
self.stderr.write(
self.style.ERROR("Cache table '%s' could not be created.\nThe error was: %s.\n" %
(tablename, e)))
View
2  django/core/management/commands/dumpdata.py
@@ -111,7 +111,7 @@ def handle(self, *app_labels, **options):
try:
return serializers.serialize(format, objects, indent=indent,
use_natural_keys=use_natural_keys)
- except Exception, e:
+ except Exception as e:
if show_traceback:
raise
raise CommandError("Unable to serialize database: %s" % e)
View
2  django/core/management/commands/flush.py
@@ -55,7 +55,7 @@ def handle_noargs(self, **options):
cursor = connection.cursor()
for sql in sql_list:
cursor.execute(sql)
- except Exception, e:
+ except Exception as e:
transaction.rollback_unless_managed(using=db)
raise CommandError("""Database %s couldn't be flushed. Possible reasons:
* The database isn't running or isn't configured correctly.
View
2  django/core/management/commands/loaddata.py
@@ -190,7 +190,7 @@ def read(self):
models.add(obj.object.__class__)
try:
obj.save(using=using)
- except (DatabaseError, IntegrityError), e:
+ except (DatabaseError, IntegrityError) as e:
msg = "Could not load %(app_label)s.%(object_name)s(pk=%(pk)s): %(error_msg)s" % {
'app_label': obj.object._meta.app_label,
'object_name': obj.object._meta.object_name,
View
2  django/core/management/commands/runserver.py
@@ -109,7 +109,7 @@ def inner_run(self, *args, **options):
handler = self.get_handler(*args, **options)
run(self.addr, int(self.port), handler,
ipv6=self.use_ipv6, threading=threading)
- except WSGIServerException, e:
+ except WSGIServerException as e:
# Use helpful error messages instead of ugly tracebacks.
ERRORS = {
13: "You don't have permission to access that port.",
View
6 django/core/management/commands/syncdb.py
@@ -37,7 +37,7 @@ def handle_noargs(self, **options):
for app_name in settings.INSTALLED_APPS:
try:
import_module('.management', app_name)
- except ImportError, exc:
+ except ImportError as exc:
# This is slightly hackish. We want to ignore ImportErrors
# if the "management" module itself is missing -- but we don't
# want to ignore the exception if the management module exists
@@ -125,7 +125,7 @@ def model_installed(model):
try:
for sql in custom_sql:
cursor.execute(sql)
- except Exception, e:
+ except Exception as e:
self.stderr.write("Failed to install custom SQL for %s.%s model: %s\n" % \
(app_name, model._meta.object_name, e))
if show_traceback:
@@ -150,7 +150,7 @@ def model_installed(model):
try:
for sql in index_sql:
cursor.execute(sql)
- except Exception, e:
+ except Exception as e:
self.stderr.write("Failed to install index for %s.%s model: %s\n" % \
(app_name, model._meta.object_name, e))
transaction.rollback_unless_managed(using=db)
View
6 django/core/management/templates.py
@@ -81,7 +81,7 @@ def handle(self, app_or_project, name, target=None, **options):
top_dir = path.join(os.getcwd(), name)
try:
os.makedirs(top_dir)
- except OSError, e:
+ except OSError as e:
if e.errno == errno.EEXIST:
message = "'%s' already exists" % top_dir
else:
@@ -231,7 +231,7 @@ def cleanup_url(url):
try:
the_path, info = urllib.urlretrieve(url,
path.join(tempdir, filename))
- except IOError, e:
+ except IOError as e:
raise CommandError("couldn't download URL %s to %s: %s" %
(url, filename, e))
@@ -286,7 +286,7 @@ def extract(self, filename):
try:
archive.extract(filename, tempdir)
return tempdir
- except (archive.ArchiveException, IOError), e:
+ except (archive.ArchiveException, IOError) as e:
raise CommandError("couldn't extract file %s to %s: %s" %
(filename, tempdir, e))
View
2  django/core/serializers/json.py
@@ -45,7 +45,7 @@ def Deserializer(stream_or_string, **options):
yield obj
except GeneratorExit:
raise
- except Exception, e:
+ except Exception as e:
# Map to deserializer error
raise DeserializationError(e)
View
2  django/core/serializers/pyyaml.py
@@ -57,6 +57,6 @@ def Deserializer(stream_or_string, **options):
yield obj
except GeneratorExit:
raise
- except Exception, e:
+ except Exception as e:
# Map to deserializer error
raise DeserializationError(e)
View
6 django/core/servers/basehttp.py
@@ -48,13 +48,13 @@ def get_internal_wsgi_application():
module_name, attr = app_path.rsplit('.', 1)
try:
mod = import_module(module_name)
- except ImportError, e:
+ except ImportError as e:
raise ImproperlyConfigured(
"WSGI application '%s' could not be loaded; "
"could not import module '%s': %s" % (app_path, module_name, e))
try:
app = getattr(mod, attr)
- except AttributeError, e:
+ except AttributeError as e:
raise ImproperlyConfigured(
"WSGI application '%s' could not be loaded; "
"can't find '%s' in module '%s': %s"
@@ -118,7 +118,7 @@ def server_bind(self):
"""Override server_bind to store the server name."""
try:
super(WSGIServer, self).server_bind()
- except Exception, e:
+ except Exception as e:
raise WSGIServerException(e)
self.setup_environ()
View
2  django/core/servers/fastcgi.py
@@ -102,7 +102,7 @@ def runfastcgi(argset=[], **kwargs):
try:
import flup
- except ImportError, e:
+ except ImportError as e:
print >> sys.stderr, "ERROR: %s" % e
print >> sys.stderr, " Unable to load the flup package. In order to run django"
print >> sys.stderr, " as a FastCGI application, you will need to get flup from"
View
4 django/core/signing.py
@@ -77,12 +77,12 @@ def get_cookie_signer(salt='django.core.signing.get_cookie_signer'):
module, attr = modpath.rsplit('.', 1)
try:
mod = import_module(module)
- except ImportError, e:
+ except ImportError as e:
raise ImproperlyConfigured(
'Error importing cookie signer %s: "%s"' % (modpath, e))
try:
Signer = getattr(mod, attr)
- except AttributeError, e:
+ except AttributeError as e:
raise ImproperlyConfigured(
'Error importing cookie signer %s: "%s"' % (modpath, e))
return Signer('django.http.cookies' + settings.SECRET_KEY, salt=salt)
View
6 django/core/urlresolvers.py
@@ -298,7 +298,7 @@ def resolve(self, path):
for pattern in self.url_patterns:
try:
sub_match = pattern.resolve(new_path)
- except Resolver404, e:
+ except Resolver404 as e:
sub_tried = e.args[0].get('tried')
if sub_tried is not None:
tried.extend([[pattern] + t for t in sub_tried])
@@ -358,7 +358,7 @@ def _reverse_with_prefix(self, lookup_view, _prefix, *args, **kwargs):
raise ValueError("Don't mix *args and **kwargs in call to reverse()!")
try:
lookup_view = get_callable(lookup_view, True)
- except (ImportError, AttributeError), e:
+ except (ImportError, AttributeError) as e:
raise NoReverseMatch("Error importing '%s': %s." % (lookup_view, e))
possibilities = self.reverse_dict.getlist(lookup_view)
prefix_norm, prefix_args = normalize(_prefix)[0]
@@ -462,7 +462,7 @@ def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None, current
extra, resolver = resolver.namespace_dict[ns]
resolved_path.append(ns)
ns_pattern = ns_pattern + extra
- except KeyError, key:
+ except KeyError as key:
if resolved_path:
raise NoReverseMatch(
"%s is not a registered namespace inside '%s'" %
View
4 django/core/validators.py
@@ -45,7 +45,7 @@ class URLValidator(RegexValidator):
def __call__(self, value):
try:
super(URLValidator, self).__call__(value)
- except ValidationError, e:
+ except ValidationError as e:
# Trivial case failed. Try for possible IDN domain
if value:
value = smart_unicode(value)
@@ -73,7 +73,7 @@ class EmailValidator(RegexValidator):
def __call__(self, value):
try:
super(EmailValidator, self).__call__(value)
- except ValidationError, e:
+ except ValidationError as e:
# Trivial case failed. Try for possible IDN domain-part
if value and u'@' in value:
parts = value.split(u'@')
View
4 django/db/backends/creation.py
@@ -329,7 +329,7 @@ def _create_test_db(self, verbosity, autoclobber):
try:
cursor.execute(
"CREATE DATABASE %s %s" % (qn(test_database_name), suffix))
- except Exception, e:
+ except Exception as e:
sys.stderr.write(
"Got an error creating the test database: %s\n" % e)
if not autoclobber:
@@ -346,7 +346,7 @@ def _create_test_db(self, verbosity, autoclobber):
cursor.execute(
"CREATE DATABASE %s %s" % (qn(test_database_name),
suffix))
- except Exception, e:
+ except Exception as e:
sys.stderr.write(
"Got an error recreating the test database: %s\n" % e)
sys.exit(2)
View
14 django/db/backends/mysql/base.py
@@ -11,7 +11,7 @@
try:
import MySQLdb as Database
-except ImportError, e:
+except ImportError as e:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
@@ -114,29 +114,29 @@ def __init__(self, cursor):
def execute(self, query, args=None):
try:
return self.cursor.execute(query, args)
- except Database.IntegrityError, e:
+ except Database.IntegrityError as e:
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
- except Database.OperationalError, e:
+ except Database.OperationalError as e:
# Map some error codes to IntegrityError, since they seem to be
# misclassified and Django would prefer the more logical place.
if e[0] in self.codes_for_integrityerror:
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
- except Database.DatabaseError, e:
+ except Database.DatabaseError as e:
raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
def executemany(self, query, args):
try:
return self.cursor.executemany(query, args)
- except Database.IntegrityError, e:
+ except Database.IntegrityError as e:
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
- except Database.OperationalError, e:
+ except Database.OperationalError as e:
# Map some error codes to IntegrityError, since they seem to be
# misclassified and Django would prefer the more logical place.
if e[0] in self.codes_for_integrityerror:
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
- except Database.DatabaseError, e:
+ except Database.DatabaseError as e:
raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
def __getattr__(self, attr):
View
16 django/db/backends/oracle/base.py
@@ -18,7 +18,7 @@ def _setup_environment(environ):
if platform.system().upper().startswith('CYGWIN'):
try:
import ctypes
- except ImportError, e:
+ except ImportError as e:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured("Error loading ctypes: %s; "
"the Oracle backend requires ctypes to "
@@ -41,7 +41,7 @@ def _setup_environment(environ):
try:
import cx_Oracle as Database
-except ImportError, e:
+except ImportError as e:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured("Error loading cx_Oracle module: %s" % e)
@@ -532,11 +532,11 @@ def _commit(self):
if self.connection is not None:
try:
return self.connection.commit()
- except Database.IntegrityError, e:
+ except Database.IntegrityError as e:
# In case cx_Oracle implements (now or in a future version)
# raising this specific exception
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
- except Database.DatabaseError, e:
+ except Database.DatabaseError as e:
# cx_Oracle 5.0.4 raises a cx_Oracle.DatabaseError exception
# with the following attributes and values:
# code = 2091
@@ -673,9 +673,9 @@ def execute(self, query, params=None):
self._guess_input_sizes([params])
try:
return self.cursor.execute(query, self._param_generator(params))
- except Database.IntegrityError, e:
+ except Database.IntegrityError as e:
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
- except Database.DatabaseError, e:
+ except Database.DatabaseError as e:
# cx_Oracle <= 4.4.0 wrongly raises a DatabaseError for ORA-01400.
if hasattr(e.args[0], 'code') and e.args[0].code == 1400 and not isinstance(e, IntegrityError):
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
@@ -702,9 +702,9 @@ def executemany(self, query, params=None):
try:
return self.cursor.executemany(query,
[self._param_generator(p) for p in formatted])
- except Database.IntegrityError, e:
+ except Database.IntegrityError as e:
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
- except Database.DatabaseError, e:
+ except Database.DatabaseError as e:
# cx_Oracle <= 4.4.0 wrongly raises a DatabaseError for ORA-01400.
if hasattr(e.args[0], 'code') and e.args[0].code == 1400 and not isinstance(e, IntegrityError):
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
View
10 django/db/backends/oracle/creation.py
@@ -62,7 +62,7 @@ def _create_test_db(self, verbosity=1, autoclobber=False):
if self._test_database_create():
try:
self._execute_test_db_creation(cursor, parameters, verbosity)
- except Exception, e:
+ except Exception as e:
sys.stderr.write("Got an error creating the test database: %s\n" % e)
if not autoclobber:
confirm = raw_input("It appears the test database, %s, already exists. Type 'yes' to delete it, or 'no' to cancel: " % TEST_NAME)
@@ -72,7 +72,7 @@ def _create_test_db(self, verbosity=1, autoclobber=False):
print "Destroying old test database '%s'..." % self.connection.alias
self._execute_test_db_destruction(cursor, parameters, verbosity)
self._execute_test_db_creation(cursor, parameters, verbosity)
- except Exception, e:
+ except Exception as e:
sys.stderr.write("Got an error recreating the test database: %s\n" % e)
sys.exit(2)
else:
@@ -84,7 +84,7 @@ def _create_test_db(self, verbosity=1, autoclobber=False):
print "Creating test user..."
try:
self._create_test_user(cursor, parameters, verbosity)
- except Exception, e:
+ except Exception as e:
sys.stderr.write("Got an error creating the test user: %s\n" % e)
if not autoclobber:
confirm = raw_input("It appears the test user, %s, already exists. Type 'yes' to delete it, or 'no' to cancel: " % TEST_USER)
@@ -96,7 +96,7 @@ def _create_test_db(self, verbosity=1, autoclobber=False):
if verbosity >= 1:
print "Creating test user..."
self._create_test_user(cursor, parameters, verbosity)
- except Exception, e:
+ except Exception as e:
sys.stderr.write("Got an error recreating the test user: %s\n" % e)
sys.exit(2)
else:
@@ -197,7 +197,7 @@ def _execute_statements(self, cursor, statements, parameters, verbosity):
print stmt
try:
cursor.execute(stmt)
- except Exception, err:
+ except Exception as err:
sys.stderr.write("Failed (%s)\n" % (err))
raise
View
12 django/db/backends/postgresql_psycopg2/base.py
@@ -20,7 +20,7 @@
try:
import psycopg2 as Database
import psycopg2.extensions
-except ImportError, e:
+except ImportError as e:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e)
@@ -50,17 +50,17 @@ def __init__(self, cursor):
def execute(self, query, args=None):
try:
return self.cursor.execute(query, args)
- except Database.IntegrityError, e:
+ except Database.IntegrityError as e:
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
- except Database.DatabaseError, e:
+ except Database.DatabaseError as e:
raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
def executemany(self, query, args):
try:
return self.cursor.executemany(query, args)
- except Database.IntegrityError, e:
+ except Database.IntegrityError as e:
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
- except Database.DatabaseError, e:
+ except Database.DatabaseError as e:
raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
def __getattr__(self, attr):
@@ -233,5 +233,5 @@ def _commit(self):
if self.connection is not None:
try:
return self.connection.commit()
- except Database.IntegrityError, e:
+ except Database.IntegrityError as e:
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
View
12 django/db/backends/sqlite3/base.py
@@ -24,9 +24,9 @@
try:
try:
from pysqlite2 import dbapi2 as Database
- except ImportError, e1:
+ except ImportError:
from sqlite3 import dbapi2 as Database
-except ImportError, exc:
+except ImportError as exc:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured("Error loading either pysqlite2 or sqlite3 modules (tried in that order): %s" % exc)
@@ -335,18 +335,18 @@ def execute(self, query, params=()):
query = self.convert_query(query)
try:
return Database.Cursor.execute(self, query, params)
- except Database.IntegrityError, e:
+ except Database.IntegrityError as e:
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
- except Database.DatabaseError, e:
+ except Database.DatabaseError as e:
raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
def executemany(self, query, param_list):
query = self.convert_query(query)
try:
return Database.Cursor.executemany(self, query, param_list)
- except Database.IntegrityError, e:
+ except Database.IntegrityError as e:
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
- except Database.DatabaseError, e:
+ except Database.DatabaseError as e:
raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
def convert_query(self, query):
View
2  django/db/backends/sqlite3/creation.py
@@ -57,7 +57,7 @@ def _create_test_db(self, verbosity, autoclobber):
if autoclobber or confirm == 'yes':
try:
os.remove(test_database_name)
- except Exception, e:
+ except Exception as e:
sys.stderr.write("Got an error deleting the old test database: %s\n" % e)
sys.exit(2)
else:
View
8 django/db/models/base.py
@@ -805,14 +805,14 @@ def full_clean(self, exclude=None):
try:
self.clean_fields(exclude=exclude)
- except ValidationError, e:
+ except ValidationError as e:
errors = e.update_error_dict(errors)
# Form.clean() is run even if other validation fails, so do the
# same with Model.clean() for consistency.
try:
self.clean()
- except ValidationError, e:
+ except ValidationError as e:
errors = e.update_error_dict(errors)
# Run unique checks, but only for fields that passed validation.
@@ -821,7 +821,7 @@ def full_clean(self, exclude=None):
exclude.append(name)
try:
self.validate_unique(exclude=exclude)
- except ValidationError, e:
+ except ValidationError as e:
errors = e.update_error_dict(errors)
if errors:
@@ -846,7 +846,7 @@ def clean_fields(self, exclude=None):
continue
try:
setattr(self, f.attname, f.clean(raw_value, self))
- except ValidationError, e:
+ except ValidationError as e:
errors[f.name] = e.messages
if errors:
View
2  django/db/models/fields/__init__.py
@@ -147,7 +147,7 @@ def run_validators(self, value):
for v in self.validators:
try:
v(value)
- except exceptions.ValidationError, e:
+ except exceptions.ValidationError as e:
if hasattr(e, 'code') and e.code in self.error_messages:
message = self.error_messages[e.code]
if e.params:
View
4 django/db/models/query.py
@@ -206,7 +206,7 @@ def __getitem__(self, k):
qs = self._clone()
qs.query.set_limits(k, k + 1)
return list(qs)[0]
- except self.model.DoesNotExist, e:
+ except self.model.DoesNotExist as e:
raise IndexError(e.args)
def __and__(self, other):
@@ -454,7 +454,7 @@ def get_or_create(self, **kwargs):
obj.save(force_insert=True, using=self.db)
transaction.savepoint_commit(sid, using=self.db)
return obj, True
- except IntegrityError, e:
+ except IntegrityError as e:
transaction.savepoint_rollback(sid, using=self.db)
exc_info = sys.exc_info()
try:
View
2  django/db/models/sql/query.py
@@ -1112,7 +1112,7 @@ def add_filter(self, filter_expr, connector=AND, negate=False, trim=False,
parts, opts, alias, True, allow_many, allow_explicit_fk=True,
can_reuse=can_reuse, negate=negate,
process_extras=process_extras)
- except MultiJoin, e:
+ except MultiJoin as e:
self.split_exclude(filter_expr, LOOKUP_SEP.join(parts[:e.level]),
can_reuse)
return
View
4 django/db/utils.py
@@ -22,7 +22,7 @@ def load_backend(backend_name):
# Look for a fully qualified database backend name
try:
return import_module('.base', backend_name)
- except ImportError, e_user:
+ except ImportError as e_user:
# The database backend wasn't found. Display a helpful error message
# listing all possible (built-in) database backends.
backend_dir = os.path.join(os.path.dirname(__file__), 'backends')
@@ -112,7 +112,7 @@ def __init__(self, routers):
try:
module_name, klass_name = r.rsplit('.', 1)
module = import_module(module_name)
- except ImportError, e:
+ except ImportError as e:
raise ImproperlyConfigured('Error importing database router %s: "%s"' % (klass_name, e))
try:
router_class = getattr(module, klass_name)
View
2  django/dispatch/dispatcher.py
@@ -205,7 +205,7 @@ def send_robust(self, sender, **named):
for receiver in self._live_receivers(_make_id(sender)):
try:
response = receiver(signal=self, sender=sender, **named)
- except Exception, err:
+ except Exception as err:
responses.append((receiver, err))
else:
responses.append((receiver, response))
View
4 django/dispatch/saferef.py
@@ -119,10 +119,10 @@ def remove(weak, self=self):
try:
if callable( function ):
function( self )
- except Exception, e:
+ except Exception as e:
try:
traceback.print_exc()
- except AttributeError, err:
+ except AttributeError as err:
print '''Exception during saferef %s cleanup function %s: %s'''%(
self, function, e
)
View
4 django/forms/fields.py
@@ -132,7 +132,7 @@ def run_validators(self, value):
for v in self.validators:
try:
v(value)
- except ValidationError, e:
+ except ValidationError as e:
if hasattr(e, 'code') and e.code in self.error_messages:
message = self.error_messages[e.code]
if e.params:
@@ -884,7 +884,7 @@ def clean(self, value):
raise ValidationError(self.error_messages['required'])
try:
clean_data.append(field.clean(field_value))
- except ValidationError, e:
+ except ValidationError as e:
# Collect all validation errors in a single list, which we'll
# raise at the end of clean(), rather than raising a single
# exception for the first error we encounter.
View
4 django/forms/forms.py
@@ -289,7 +289,7 @@ def _clean_fields(self):
if hasattr(self, 'clean_%s' % name):
value = getattr(self, 'clean_%s' % name)()
self.cleaned_data[name] = value
- except ValidationError, e:
+ except ValidationError as e:
self._errors[name] = self.error_class(e.messages)
if name in self.cleaned_data:
del self.cleaned_data[name]
@@ -297,7 +297,7 @@ def _clean_fields(self):
def _clean_form(self):
try:
self.cleaned_data = self.clean()
- except ValidationError, e:
+ except ValidationError as e:
self._errors[NON_FIELD_ERRORS] = self.error_class(e.messages)
def _post_clean(self):
View
2  django/forms/formsets.py
@@ -291,7 +291,7 @@ def full_clean(self):
# Give self.clean() a chance to do cross-form validation.
try:
self.clean()
- except ValidationError, e:
+ except ValidationError as e:
self._non_form_errors = self.error_class(e.messages)
def clean(self):
View
6 django/forms/models.py
@@ -324,13 +324,13 @@ def _post_clean(self):
# Clean the model instance's fields.
try:
self.instance.clean_fields(exclude=exclude)
- except ValidationError, e:
+ except ValidationError as e:
self._update_errors(e.message_dict)
# Call the model instance's clean method.
try:
self.instance.clean()
- except ValidationError, e:
+ except ValidationError as e:
self._update_errors({NON_FIELD_ERRORS: e.messages})
# Validate uniqueness if needed.
@@ -345,7 +345,7 @@ def validate_unique(self):
exclude = self._get_validation_exclusions()
try:
self.instance.validate_unique(exclude=exclude)
- except ValidationError, e:
+ except ValidationError as e:
self._update_errors(e.message_dict)
def save(self, commit=True):
View
2  django/forms/util.py
@@ -66,7 +66,7 @@ def from_current_timezone(value):
current_timezone = timezone.get_current_timezone()
try:
return timezone.make_aware(value, current_timezone)
- except Exception, e:
+ except Exception:
raise ValidationError(_('%(datetime)s couldn\'t be interpreted '
'in time zone %(current_timezone)s; it '
'may be ambiguous or it may not exist.')
View
4 django/http/__init__.py
@@ -290,7 +290,7 @@ def body(self):
raise Exception("You cannot access body after reading from request's data stream")
try:
self._body = self.read()
- except IOError, e:
+ except IOError as e:
raise UnreadablePostError, e, sys.exc_traceback
self._stream = StringIO(self._body)
return self._body
@@ -556,7 +556,7 @@ def _convert_to_ascii(self, *values):
if isinstance(value, unicode):
try:
value = value.encode('us-ascii')
- except UnicodeError, e:
+ except UnicodeError as e:
e.reason += ', HTTP response headers must be in US-ASCII format'
raise
else:
View
6 django/http/multipartparser.py
@@ -196,7 +196,7 @@ def parse(self):
# We only special-case base64 transfer encoding
try:
chunk = str(chunk).decode('base64')
- except Exception, e:
+ except Exception as e:
# Since this is only a chunk, any error is an unfixable error.
raise MultiPartParserError("Could not decode base64 data: %r" % e)
@@ -209,7 +209,7 @@ def parse(self):
# If the chunk received by the handler is None, then don't continue.
break
- except SkipFile, e:
+ except SkipFile:
# Just use up the rest of this file...
exhaust(field_stream)
else:
@@ -218,7 +218,7 @@ def parse(self):
else:
# If this is neither a FIELD or a FILE, just exhaust the stream.
exhaust(stream)
- except StopUpload, e:
+ except StopUpload as e:
if not e.connection_reset:
exhaust(self._input_data)
else:
View
6 django/template/base.py
@@ -265,7 +265,7 @@ def parse(self, parse_until=None):
self.invalid_block_tag(token, command, parse_until)
try:
compiled_result = compile_func(self, token)
- except TemplateSyntaxError, e:
+ except TemplateSyntaxError as e:
if not self.compile_function_error(token, e):
raise
self.extend_nodelist(nodelist, compiled_result, token)
@@ -774,7 +774,7 @@ def _resolve_lookup(self, context):
# GOTCHA: This will also catch any TypeError
# raised in the function itself.
current = settings.TEMPLATE_STRING_IF_INVALID # invalid method call
- except Exception, e:
+ except Exception as e:
if getattr(e, 'silent_variable_failure', False):
current = settings.TEMPLATE_STRING_IF_INVALID
else:
@@ -1237,7 +1237,7 @@ def import_library(taglib_module):
"""
try:
mod = import_module(taglib_module)
- except ImportError, e:
+ except ImportError as e:
# If the ImportError is because the taglib submodule does not exist,
# that's not an error that should be raised. If the submodule exists
# and raised an ImportError on the attempt to load it, that we want
View
2  django/template/context.py
@@ -150,7 +150,7 @@ def get_standard_processors():
module, attr = path[:i], path[i+1:]
try:
mod = import_module(module)
- except ImportError, e:
+ except ImportError as e:
raise ImproperlyConfigured('Error importing request processor module %s: "%s"' % (module, e))
try:
func = getattr(mod, attr)
View
4 django/template/debug.py
@@ -72,7 +72,7 @@ class DebugNodeList(NodeList):
def render_node(self, node, context):
try:
return node.render(context)
- except Exception, e:
+ except Exception as e:
if not hasattr(e, 'django_template_source'):
e.django_template_source = node.source
raise
@@ -87,7 +87,7 @@ def render(self, context):
output = force_unicode(output)
except UnicodeDecodeError:
return ''
- except Exception, e:
+ except Exception as e:
if not hasattr(e, 'django_template_source'):
e.django_template_source = self.source
raise
View
2  django/template/defaultfilters.py
@@ -892,5 +892,5 @@ def pprint(value):
"""A wrapper around pprint.pprint -- for debugging, really."""
try:
return pformat(value)
- except Exception, e:
+ except Exception as e:
return u"Error in formatting: %s" % force_unicode(e, errors="replace")
View
10 django/template/defaulttags.py
@@ -183,7 +183,7 @@ def render(self, context):
for node in self.nodelist_loop:
try:
nodelist.append(node.render(context))
- except Exception, e:
+ except Exception as e:
if not hasattr(e, 'django_template_source'):
e.django_template_source = node.source
raise
@@ -337,7 +337,7 @@ def render(self, context):
try:
t = Template(output, name=filepath)
return t.render(context)
- except TemplateSyntaxError, e:
+ except TemplateSyntaxError as e:
if settings.DEBUG:
return "[Included template had syntax error: %s]" % e
else:
@@ -403,7 +403,7 @@ def render(self, context):
url = ''
try:
url = reverse(view_name, args=args, kwargs=kwargs, current_app=context.current_app)
- except NoReverseMatch, e:
+ except NoReverseMatch as e:
if settings.SETTINGS_MODULE:
project_name = settings.SETTINGS_MODULE.split('.')[0]
try:
@@ -1005,7 +1005,7 @@ def load(parser, token):
try:
taglib = bits[-1]
lib = get_library(taglib)
- except InvalidTemplateLibrary, e:
+ except InvalidTemplateLibrary as e:
raise TemplateSyntaxError("'%s' is not a valid tag library: %s" %
(taglib, e))
else:
@@ -1028,7 +1028,7 @@ def load(parser, token):
try:
lib = get_library(taglib)
parser.add_library(lib)
- except InvalidTemplateLibrary, e:
+ except InvalidTemplateLibrary as e:
raise TemplateSyntaxError("'%s' is not a valid tag library: %s" %
(taglib, e))
return LoadNode()
View
6 django/template/loader.py
@@ -93,11 +93,11 @@ def find_template_loader(loader):
module, attr = loader.rsplit('.', 1)
try:
mod = import_module(module)
- except ImportError, e:
+ except ImportError as e:
raise ImproperlyConfigured('Error importing template source loader %s: "%s"' % (loader, e))
try:
TemplateLoader = getattr(mod, attr)
- except AttributeError, e:
+ except AttributeError as e:
raise ImproperlyConfigured('Error importing template source loader %s: "%s"' % (loader, e))
if hasattr(TemplateLoader, 'load_template_source'):
@@ -185,7 +185,7 @@ def select_template(template_name_list):
for template_name in template_name_list:
try:
return get_template(template_name)
- except TemplateDoesNotExist, e:
+ except TemplateDoesNotExist as e:
if e.args[0] not in not_found:
not_found.append(e.args[0])
continue
View
2  django/template/loaders/app_directories.py
@@ -19,7 +19,7 @@
for app in settings.INSTALLED_APPS:
try:
mod = import_module(app)
- except ImportError, e:
+ except ImportError as e:
raise ImproperlyConfigured('ImportError %s: %s' % (app, e.args[0]))
template_dir = os.path.join(os.path.dirname(mod.__file__), 'templates')
if os.path.isdir(template_dir):
View
8 django/test/_doctest.py
@@ -1626,7 +1626,7 @@ class DebugRunner(DocTestRunner):
... {}, 'foo', 'foo.py', 0)
>>> try:
... runner.run(test)
- ... except UnexpectedException, failure:
+ ... except UnexpectedException as failure:
... pass
>>> failure.test is test
@@ -1654,7 +1654,7 @@ class DebugRunner(DocTestRunner):
>>> try:
... runner.run(test)
- ... except DocTestFailure, failure:
+ ... except DocTestFailure as failure:
... pass
DocTestFailure objects provide access to the test:
@@ -2164,7 +2164,7 @@ def debug(self):
>>> case = DocTestCase(test)
>>> try:
... case.debug()
- ... except UnexpectedException, failure:
+ ... except UnexpectedException as failure:
... pass
The UnexpectedException contains the test, the example, and
@@ -2193,7 +2193,7 @@ def debug(self):
>>> try:
... case.debug()
- ... except DocTestFailure, failure:
+ ... except DocTestFailure as failure:
... pass
DocTestFailure objects provide access to the test:
View
2  django/test/client.py
@@ -378,7 +378,7 @@ def request(self, **request):
try:
response = self.handler(environ)
- except TemplateDoesNotExist, e:
+ except TemplateDoesNotExist as e:
# If the view raises an exception, Django will attempt to show
# the 500.html template. If that template is not available,
# we should ignore the error in favor of re-raising the
View
6 django/test/testcases.py
@@ -84,7 +84,7 @@ def restore_transaction_methods():
def assert_and_parse_html(self, html, user_msg, msg):
try:
dom = parse_html(html)
- except HTMLParseError, e:
+ except HTMLParseError as e:
standardMsg = u'%s\n%s' % (msg, e.msg)
self.fail(self._formatMessage(user_msg, standardMsg))
return dom
@@ -1035,7 +1035,7 @@ def run(self):
try:
self.httpd = StoppableWSGIServer(
(self.host, port), QuietWSGIRequestHandler)
- except WSGIServerException, e:
+ except WSGIServerException as e:
if (index + 1 < len(self.possible_ports) and
e.args[0].errno == errno.EADDRINUSE):
# This port is already in use, so we go on and try with
@@ -1054,7 +1054,7 @@ def run(self):
self.httpd.set_app(handler)
self.is_ready.set()
self.httpd.serve_forever()
- except Exception, e:
+ except Exception as e:
self.error = e
self.is_ready.set()
View
4 django/utils/daemonize.py
@@ -9,7 +9,7 @@ def become_daemon(our_home_dir='.', out_log='/dev/null',
try:
if os.fork() > 0:
sys.exit(0) # kill off parent
- except OSError, e:
+ except OSError as e:
sys.stderr.write("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror))
sys.exit(1)
os.setsid()
@@ -20,7 +20,7 @@ def become_daemon(our_home_dir='.', out_log='/dev/null',
try:
if os.fork() > 0:
os._exit(0)
- except OSError, e:
+ except OSError as e:
sys.stderr.write("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror))
os._exit(1)
View
2  django/utils/decorators.py
@@ -89,7 +89,7 @@ def _wrapped_view(request, *args, **kwargs):
return result
try:
response = view_func(request, *args, **kwargs)
- except Exception, e:
+ except Exception as e:
if hasattr(middleware, 'process_exception'):
result = middleware.process_exception(request, e)
if result is not None:
View
28 django/utils/dictconfig.py
@@ -297,21 +297,21 @@ def configure(self):
level = handler_config.get('level', None)
if level:
handler.setLevel(_checkLevel(level))
- except StandardError, e:
+ except StandardError as e:
raise ValueError('Unable to configure handler '
'%r: %s' % (name, e))
loggers = config.get('loggers', EMPTY_DICT)
for name in loggers:
try:
self.configure_logger(name, loggers[name], True)
- except StandardError, e:
+ except StandardError as e:
raise ValueError('Unable to configure logger '
'%r: %s' % (name, e))
root = config.get('root', None)
if root:
try:
self.configure_root(root, True)
- except StandardError, e:
+ except StandardError as e:
raise ValueError('Unable to configure root '
'logger: %s' % e)
else:
@@ -326,7 +326,7 @@ def configure(self):
try:
formatters[name] = self.configure_formatter(
formatters[name])
- except StandardError, e:
+ except StandardError as e:
raise ValueError('Unable to configure '
'formatter %r: %s' % (name, e))
# Next, do filters - they don't refer to anything else, either
@@ -334,7 +334,7 @@ def configure(self):
for name in filters:
try:
filters[name] = self.configure_filter(filters[name])
- except StandardError, e:
+ except StandardError as e:
raise ValueError('Unable to configure '
'filter %r: %s' % (name, e))
@@ -347,7 +347,7 @@ def configure(self):