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).
This commit is contained in:
Claude Paroz 2012-04-28 18:09:37 +02:00
parent eefb00f301
commit 3904b74a3f
107 changed files with 306 additions and 354 deletions

View File

@ -91,7 +91,7 @@ class Settings(BaseSettings):
try:
mod = importlib.import_module(self.SETTINGS_MODULE)
except ImportError, e:
except ImportError as e:
raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))
# Settings that should be converted into tuples if they're mistakenly entered

View File

@ -14,7 +14,7 @@ class AdminSeleniumWebDriverTestCase(LiveServerTestCase):
mod = import_module(module)
WebDriver = getattr(mod, attr)
cls.selenium = WebDriver()
except Exception, e:
except Exception as e:
raise SkipTest('Selenium webdriver "%s" not installed or not '
'operational: %s' % (cls.webdriver_class, str(e)))
super(AdminSeleniumWebDriverTestCase, cls).setUpClass()

View File

@ -156,7 +156,7 @@ class NestedObjects(Collector):
self.add_edge(None, obj)
try:
return super(NestedObjects, self).collect(objs, source_attr=source_attr, **kwargs)
except models.ProtectedError, e:
except models.ProtectedError as e:
self.protected.update(e.protected_objects)
def related_objects(self, related, objs):

View File

@ -139,7 +139,7 @@ class ChangeList(object):
use_distinct = (use_distinct or
lookup_needs_distinct(self.lookup_opts, key))
return filter_specs, bool(filter_specs), lookup_params, use_distinct
except FieldDoesNotExist, e:
except FieldDoesNotExist as e:
raise IncorrectLookupParameters(e)
def get_query_string(self, new_params=None, remove=None):
@ -316,7 +316,7 @@ class ChangeList(object):
# Allow certain types of errors to be re-raised as-is so that the
# caller can treat them in a special way.
raise
except Exception, e:
except Exception as e:
# Every other error is caught with a naked except, because we don't
# have any other way of validating lookup parameters. They might be
# invalid if the keyword arguments are incorrect, or if the values

View File

@ -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 File

@ -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 File

@ -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 File

@ -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 File

@ -164,13 +164,13 @@ class SpatialRefSysMixin(object):
try:
self._srs = gdal.SpatialReference(self.wkt)
return self.srs
except Exception, msg:
except Exception as msg:
pass
try:
self._srs = gdal.SpatialReference(self.proj4text)
return self.srs
except Exception, msg:
except Exception as msg:
pass
raise Exception('Could not get OSR SpatialReference from WKT: %s\nError:\n%s' % (self.wkt, msg))

View File

@ -16,7 +16,7 @@ class OracleIntrospection(DatabaseIntrospection):
cursor.execute('SELECT "DIMINFO", "SRID" FROM "USER_SDO_GEOM_METADATA" WHERE "TABLE_NAME"=%s AND "COLUMN_NAME"=%s',
(table_name.upper(), geo_col.upper()))
row = cursor.fetchone()
except Exception, msg:
except Exception as msg:
raise Exception('Could not find entry in USER_SDO_GEOM_METADATA corresponding to "%s"."%s"\n'
'Error message: %s.' % (table_name, geo_col, msg))

View File

@ -107,9 +107,7 @@ class PostGISOperations(DatabaseOperations, BaseSpatialOperations):
'Was the database created from a spatial database '
'template?' % self.connection.settings_dict['NAME']
)
except Exception, e:
# TODO: Raise helpful exceptions as they become known.
raise
# TODO: Raise helpful exceptions as they become known.
# PostGIS-specific operators. The commented descriptions of these
# operators come from Section 7.6 of the PostGIS 1.4 documentation.

View File

@ -56,7 +56,7 @@ class DatabaseWrapper(SQLiteDatabaseWrapper):
cur = self.connection.cursor(factory=SQLiteCursorWrapper)
try:
cur.execute("SELECT load_extension(%s)", (self.spatialite_lib,))
except Exception, msg:
except Exception as msg:
raise ImproperlyConfigured('Unable to load the SpatiaLite library extension '
'"%s" because: %s' % (self.spatialite_lib, msg))
return cur

View File

@ -122,7 +122,7 @@ class SpatiaLiteOperations(DatabaseOperations, BaseSpatialOperations):
self.spatial_version = version
except ImproperlyConfigured:
raise
except Exception, msg:
except Exception as msg:
raise ImproperlyConfigured('Cannot determine the SpatiaLite version for the "%s" '
'database (error was "%s"). Was the SpatiaLite initialization '
'SQL loaded on this database?' %

View File

@ -6,10 +6,10 @@ geom_backend = getattr(settings, 'GEOMETRY_BACKEND', 'geos')
try:
module = import_module('.%s' % geom_backend, 'django.contrib.gis.geometry.backend')
except ImportError, e:
except ImportError:
try:
module = import_module(geom_backend)
except ImportError, e_user:
except ImportError:
raise ImproperlyConfigured('Could not import user-defined GEOMETRY_BACKEND '
'"%s".' % geom_backend)

View File

@ -87,7 +87,7 @@ class Command(LabelCommand):
# Getting the OGR DataSource from the string parameter.
try:
ds = gdal.DataSource(data_source)
except gdal.OGRException, msg:
except gdal.OGRException as msg:
raise CommandError(msg)
# Whether the user wants to generate the LayerMapping dictionary as well.

View File

@ -62,32 +62,20 @@ class DistanceTest(unittest.TestCase):
d4 -= d1
self.assertEqual(d4.m, -200)
try:
with self.assertRaises(TypeError):
d5 = d1 + 1
except TypeError, e:
pass
else:
self.fail('Distance + number should raise TypeError')
try:
with self.assertRaises(TypeError):
d5 = d1 - 1
except TypeError, e:
pass
else:
self.fail('Distance - number should raise TypeError')
try:
with self.assertRaises(TypeError):
d1 += 1
except TypeError, e:
pass
else:
self.fail('Distance += number should raise TypeError')
try:
with self.assertRaises(TypeError):
d1 -= 1
except TypeError, e:
pass
else:
self.fail('Distance -= number should raise TypeError')
def testMultiplication(self):
@ -110,25 +98,16 @@ class DistanceTest(unittest.TestCase):
self.assertTrue(isinstance(a5, Area))
self.assertEqual(a5.sq_m, 100*10)
try:
with self.assertRaises(TypeError):
d1 *= D(m=1)
except TypeError, e:
pass
else:
self.fail('Distance *= Distance should raise TypeError')
try:
with self.assertRaises(TypeError):
d5 = d1 / D(m=1)
except TypeError, e:
pass
else:
self.fail('Distance / Distance should raise TypeError')
try:
with self.assertRaises(TypeError):
d1 /= D(m=1)
except TypeError, e:
pass
else:
self.fail('Distance /= Distance should raise TypeError')
def testUnitConversions(self):
@ -217,32 +196,20 @@ class AreaTest(unittest.TestCase):
a4 -= a1
self.assertEqual(a4.sq_m, -200)
try:
with self.assertRaises(TypeError):
a5 = a1 + 1
except TypeError, e:
pass
else:
self.fail('Area + number should raise TypeError')
try:
with self.assertRaises(TypeError):
a5 = a1 - 1
except TypeError, e:
pass
else:
self.fail('Area - number should raise TypeError')
try:
with self.assertRaises(TypeError):
a1 += 1
except TypeError, e:
pass
else:
self.fail('Area += number should raise TypeError')
try:
with self.assertRaises(TypeError):
a1 -= 1
except TypeError, e:
pass
else:
self.fail('Area -= number should raise TypeError')
def testMultiplication(self):
@ -261,32 +228,20 @@ class AreaTest(unittest.TestCase):
a4 /= 5
self.assertEqual(a4.sq_m, 10)
try:
with self.assertRaises(TypeError):
a5 = a1 * A(sq_m=1)
except TypeError, e:
pass
else:
self.fail('Area * Area should raise TypeError')
try:
with self.assertRaises(TypeError):
a1 *= A(sq_m=1)
except TypeError, e:
pass
else:
self.fail('Area *= Area should raise TypeError')
try:
with self.assertRaises(TypeError):
a5 = a1 / A(sq_m=1)
except TypeError, e:
pass
else:
self.fail('Area / Area should raise TypeError')
try:
with self.assertRaises(TypeError):
a1 /= A(sq_m=1)
except TypeError, e:
pass
else:
self.fail('Area /= Area should raise TypeError')
def testUnitConversions(self):

View File

@ -430,7 +430,7 @@ class LayerMapping(object):
# Creating the CoordTransform object
return CoordTransform(self.source_srs, target_srs)
except Exception, msg:
except Exception as msg:
raise LayerMapError('Could not translate between the data source and model geometry: %s' % msg)
def geometry_field(self):
@ -514,7 +514,7 @@ class LayerMapping(object):
# Getting the keyword arguments
try:
kwargs = self.feature_kwargs(feat)
except LayerMapError, msg:
except LayerMapError as msg:
# Something borked the validation
if strict: raise
elif not silent:
@ -553,7 +553,7 @@ class LayerMapping(object):
if verbose: stream.write('%s: %s\n' % (is_update and 'Updated' or 'Saved', m))
except SystemExit:
raise
except Exception, msg:
except Exception as msg:
if self.transaction_mode == 'autocommit':
# Rolling back the transaction so that other model saves
# will work.

View File

@ -87,7 +87,7 @@ Paragraph 2 with a link_
# Docutils v0.4 and earlier
self.assertEqual(rendered, """<p>Paragraph 1</p>
<p>Paragraph 2 with a <a class="reference" href="http://www.example.com/">link</a></p>""")
except AssertionError, e:
except AssertionError:
# Docutils from SVN (which will become 0.5)
self.assertEqual(rendered, """<p>Paragraph 1</p>
<p>Paragraph 2 with a <a class="reference external" href="http://www.example.com/">link</a></p>""")

View File

@ -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 File

@ -90,7 +90,7 @@ class SessionStore(SessionBase):
fd = os.open(session_file_name, flags)
os.close(fd)
except OSError, e:
except OSError as e:
if must_create and e.errno == errno.EEXIST:
raise CreateError
raise

View File

@ -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 File

@ -56,7 +56,7 @@ class StaticFilesHandler(WSGIHandler):
if self._should_handle(request.path):
try:
return self.serve(request)
except Http404, e:
except Http404 as e:
if settings.DEBUG:
from django.views import debug
return debug.technical_404_response(request, e)

View File

@ -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 File

@ -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 File

@ -166,7 +166,7 @@ class FileSystemStorage(Storage):
if not os.path.exists(directory):
try:
os.makedirs(directory)
except OSError, e:
except OSError as e:
if e.errno != errno.EEXIST:
raise
if not os.path.isdir(directory):
@ -197,7 +197,7 @@ class FileSystemStorage(Storage):
finally:
locks.unlock(fd)
os.close(fd)
except OSError, e:
except OSError as e:
if e.errno == errno.EEXIST:
# Ooops, the file exists. We need a new file name.
name = self.get_available_name(name)
@ -222,7 +222,7 @@ class FileSystemStorage(Storage):
if os.path.exists(name):
try:
os.remove(name)
except OSError, e:
except OSError as e:
if e.errno != errno.ENOENT:
raise
@ -273,7 +273,7 @@ def get_storage_class(import_path=None):
module, classname = import_path[:dot], import_path[dot+1:]
try:
mod = import_module(module)
except ImportError, e:
except ImportError as e:
raise ImproperlyConfigured('Error importing storage module %s: "%s"' % (module, e))
try:
return getattr(mod, classname)

View File

@ -75,7 +75,7 @@ class TemporaryUploadedFile(UploadedFile):
def close(self):
try:
return self.file.close()
except OSError, e:
except OSError as e:
if e.errno != 2:
# Means the file was moved or deleted before the tempfile
# could unlink it. Still sets self.file.close_called and

View File

@ -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 File

@ -43,7 +43,7 @@ class BaseHandler(object):
raise exceptions.ImproperlyConfigured('%s isn\'t a middleware module' % middleware_path)
try:
mod = import_module(mw_module)
except ImportError, e:
except ImportError as e:
raise exceptions.ImproperlyConfigured('Error importing middleware %s: "%s"' % (mw_module, e))
try:
mw_class = getattr(mod, mw_classname)
@ -109,7 +109,7 @@ class BaseHandler(object):
if response is None:
try:
response = callback(request, *callback_args, **callback_kwargs)
except Exception, e:
except Exception as e:
# If the view raised an exception, run it through exception
# middleware, and if the exception middleware returns a
# response, use that. Otherwise, reraise the exception.
@ -135,7 +135,7 @@ class BaseHandler(object):
response = middleware_method(request, response)
response = response.render()
except http.Http404, e:
except http.Http404 as e:
logger.warning('Not Found: %s', request.path,
extra={
'status_code': 404,

View File

@ -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 File

@ -25,7 +25,7 @@ class EmailBackend(ConsoleEmailBackend):
elif not os.path.exists(self.file_path):
try:
os.makedirs(self.file_path)
except OSError, err:
except OSError as err:
raise ImproperlyConfigured('Could not create directory for saving email messages: %s (%s)' % (self.file_path, err))
# Make sure that self.file_path is writable.
if not os.access(self.file_path, os.W_OK):

View File

@ -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 File

@ -214,7 +214,7 @@ class BaseCommand(object):
from django.utils import translation
saved_lang = translation.get_language()
translation.activate('en-us')
except ImportError, e:
except ImportError as e:
# If settings should be available, but aren't,
# raise the error and quit.
if show_traceback:
@ -240,7 +240,7 @@ class BaseCommand(object):
self.stdout.write(output)
if self.output_transaction:
self.stdout.write('\n' + self.style.SQL_KEYWORD("COMMIT;") + '\n')
except CommandError, e:
except CommandError as e:
if show_traceback:
traceback.print_exc()
else:
@ -297,7 +297,7 @@ class AppCommand(BaseCommand):
raise CommandError('Enter at least one appname.')
try:
app_list = [models.get_app(app_label) for app_label in app_labels]
except (ImproperlyConfigured, ImportError), e:
except (ImproperlyConfigured, ImportError) as e:
raise CommandError("%s. Are you sure your INSTALLED_APPS setting is correct?" % e)
output = []
for app in app_list:

View File

@ -54,7 +54,7 @@ class Command(LabelCommand):
curs = connection.cursor()
try:
curs.execute("\n".join(full_statement))
except DatabaseError, e:
except DatabaseError as e:
self.stderr.write(
self.style.ERROR("Cache table '%s' could not be created.\nThe error was: %s.\n" %
(tablename, e)))

View File

@ -111,7 +111,7 @@ class Command(BaseCommand):
try:
return serializers.serialize(format, objects, indent=indent,
use_natural_keys=use_natural_keys)
except Exception, e:
except Exception as e:
if show_traceback:
raise
raise CommandError("Unable to serialize database: %s" % e)

View File

@ -55,7 +55,7 @@ Are you sure you want to do this?
cursor = connection.cursor()
for sql in sql_list:
cursor.execute(sql)
except Exception, e:
except Exception as e:
transaction.rollback_unless_managed(using=db)
raise CommandError("""Database %s couldn't be flushed. Possible reasons:
* The database isn't running or isn't configured correctly.

View File

@ -190,7 +190,7 @@ class Command(BaseCommand):
models.add(obj.object.__class__)
try:
obj.save(using=using)
except (DatabaseError, IntegrityError), e:
except (DatabaseError, IntegrityError) as e:
msg = "Could not load %(app_label)s.%(object_name)s(pk=%(pk)s): %(error_msg)s" % {
'app_label': obj.object._meta.app_label,
'object_name': obj.object._meta.object_name,

View File

@ -109,7 +109,7 @@ class Command(BaseCommand):
handler = self.get_handler(*args, **options)
run(self.addr, int(self.port), handler,
ipv6=self.use_ipv6, threading=threading)
except WSGIServerException, e:
except WSGIServerException as e:
# Use helpful error messages instead of ugly tracebacks.
ERRORS = {
13: "You don't have permission to access that port.",

View File

@ -37,7 +37,7 @@ class Command(NoArgsCommand):
for app_name in settings.INSTALLED_APPS:
try:
import_module('.management', app_name)
except ImportError, exc:
except ImportError as exc:
# This is slightly hackish. We want to ignore ImportErrors
# if the "management" module itself is missing -- but we don't
# want to ignore the exception if the management module exists
@ -125,7 +125,7 @@ class Command(NoArgsCommand):
try:
for sql in custom_sql:
cursor.execute(sql)
except Exception, e:
except Exception as e:
self.stderr.write("Failed to install custom SQL for %s.%s model: %s\n" % \
(app_name, model._meta.object_name, e))
if show_traceback:
@ -150,7 +150,7 @@ class Command(NoArgsCommand):
try:
for sql in index_sql:
cursor.execute(sql)
except Exception, e:
except Exception as e:
self.stderr.write("Failed to install index for %s.%s model: %s\n" % \
(app_name, model._meta.object_name, e))
transaction.rollback_unless_managed(using=db)

View File

@ -81,7 +81,7 @@ class TemplateCommand(BaseCommand):
top_dir = path.join(os.getcwd(), name)
try:
os.makedirs(top_dir)
except OSError, e:
except OSError as e:
if e.errno == errno.EEXIST:
message = "'%s' already exists" % top_dir
else:
@ -231,7 +231,7 @@ class TemplateCommand(BaseCommand):
try:
the_path, info = urllib.urlretrieve(url,
path.join(tempdir, filename))
except IOError, e:
except IOError as e:
raise CommandError("couldn't download URL %s to %s: %s" %
(url, filename, e))
@ -286,7 +286,7 @@ class TemplateCommand(BaseCommand):
try:
archive.extract(filename, tempdir)
return tempdir
except (archive.ArchiveException, IOError), e:
except (archive.ArchiveException, IOError) as e:
raise CommandError("couldn't extract file %s to %s: %s" %
(filename, tempdir, e))

View File

@ -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 File

@ -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 File

@ -48,13 +48,13 @@ def get_internal_wsgi_application():
module_name, attr = app_path.rsplit('.', 1)
try:
mod = import_module(module_name)
except ImportError, e:
except ImportError as e:
raise ImproperlyConfigured(
"WSGI application '%s' could not be loaded; "
"could not import module '%s': %s" % (app_path, module_name, e))
try:
app = getattr(mod, attr)
except AttributeError, e:
except AttributeError as e:
raise ImproperlyConfigured(
"WSGI application '%s' could not be loaded; "
"can't find '%s' in module '%s': %s"
@ -118,7 +118,7 @@ class WSGIServer(simple_server.WSGIServer, object):
"""Override server_bind to store the server name."""
try:
super(WSGIServer, self).server_bind()
except Exception, e:
except Exception as e:
raise WSGIServerException(e)
self.setup_environ()

View File

@ -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 File

@ -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 File

@ -298,7 +298,7 @@ class RegexURLResolver(LocaleRegexProvider):
for pattern in self.url_patterns:
try:
sub_match = pattern.resolve(new_path)
except Resolver404, e:
except Resolver404 as e:
sub_tried = e.args[0].get('tried')
if sub_tried is not None:
tried.extend([[pattern] + t for t in sub_tried])
@ -358,7 +358,7 @@ class RegexURLResolver(LocaleRegexProvider):
raise ValueError("Don't mix *args and **kwargs in call to reverse()!")
try:
lookup_view = get_callable(lookup_view, True)
except (ImportError, AttributeError), e:
except (ImportError, AttributeError) as e:
raise NoReverseMatch("Error importing '%s': %s." % (lookup_view, e))
possibilities = self.reverse_dict.getlist(lookup_view)
prefix_norm, prefix_args = normalize(_prefix)[0]
@ -462,7 +462,7 @@ def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None, current
extra, resolver = resolver.namespace_dict[ns]
resolved_path.append(ns)
ns_pattern = ns_pattern + extra
except KeyError, key:
except KeyError as key:
if resolved_path:
raise NoReverseMatch(
"%s is not a registered namespace inside '%s'" %

View File

@ -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 File

@ -329,7 +329,7 @@ class BaseDatabaseCreation(object):
try:
cursor.execute(
"CREATE DATABASE %s %s" % (qn(test_database_name), suffix))
except Exception, e:
except Exception as e:
sys.stderr.write(
"Got an error creating the test database: %s\n" % e)
if not autoclobber:
@ -346,7 +346,7 @@ class BaseDatabaseCreation(object):
cursor.execute(
"CREATE DATABASE %s %s" % (qn(test_database_name),
suffix))
except Exception, e:
except Exception as e:
sys.stderr.write(
"Got an error recreating the test database: %s\n" % e)
sys.exit(2)

View File

@ -11,7 +11,7 @@ import warnings
try:
import MySQLdb as Database
except ImportError, e:
except ImportError as e:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
@ -114,29 +114,29 @@ class CursorWrapper(object):
def execute(self, query, args=None):
try:
return self.cursor.execute(query, args)
except Database.IntegrityError, e:
except Database.IntegrityError as e:
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
except Database.OperationalError, e:
except Database.OperationalError as e:
# Map some error codes to IntegrityError, since they seem to be
# misclassified and Django would prefer the more logical place.
if e[0] in self.codes_for_integrityerror:
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
except Database.DatabaseError, e:
except Database.DatabaseError as e:
raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
def executemany(self, query, args):
try:
return self.cursor.executemany(query, args)
except Database.IntegrityError, e:
except Database.IntegrityError as e:
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
except Database.OperationalError, e:
except Database.OperationalError as e:
# Map some error codes to IntegrityError, since they seem to be
# misclassified and Django would prefer the more logical place.
if e[0] in self.codes_for_integrityerror:
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
except Database.DatabaseError, e:
except Database.DatabaseError as e:
raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
def __getattr__(self, attr):

View File

@ -18,7 +18,7 @@ def _setup_environment(environ):
if platform.system().upper().startswith('CYGWIN'):
try:
import ctypes
except ImportError, e:
except ImportError as e:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured("Error loading ctypes: %s; "
"the Oracle backend requires ctypes to "
@ -41,7 +41,7 @@ _setup_environment([
try:
import cx_Oracle as Database
except ImportError, e:
except ImportError as e:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured("Error loading cx_Oracle module: %s" % e)
@ -532,11 +532,11 @@ class DatabaseWrapper(BaseDatabaseWrapper):
if self.connection is not None:
try:
return self.connection.commit()
except Database.IntegrityError, e:
except Database.IntegrityError as e:
# In case cx_Oracle implements (now or in a future version)
# raising this specific exception
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
except Database.DatabaseError, e:
except Database.DatabaseError as e:
# cx_Oracle 5.0.4 raises a cx_Oracle.DatabaseError exception
# with the following attributes and values:
# code = 2091
@ -673,9 +673,9 @@ class FormatStylePlaceholderCursor(object):
self._guess_input_sizes([params])
try:
return self.cursor.execute(query, self._param_generator(params))
except Database.IntegrityError, e:
except Database.IntegrityError as e:
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
except Database.DatabaseError, e:
except Database.DatabaseError as e:
# cx_Oracle <= 4.4.0 wrongly raises a DatabaseError for ORA-01400.
if hasattr(e.args[0], 'code') and e.args[0].code == 1400 and not isinstance(e, IntegrityError):
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
@ -702,9 +702,9 @@ class FormatStylePlaceholderCursor(object):
try:
return self.cursor.executemany(query,
[self._param_generator(p) for p in formatted])
except Database.IntegrityError, e:
except Database.IntegrityError as e:
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
except Database.DatabaseError, e:
except Database.DatabaseError as e:
# cx_Oracle <= 4.4.0 wrongly raises a DatabaseError for ORA-01400.
if hasattr(e.args[0], 'code') and e.args[0].code == 1400 and not isinstance(e, IntegrityError):
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]

View File

@ -62,7 +62,7 @@ class DatabaseCreation(BaseDatabaseCreation):
if self._test_database_create():
try:
self._execute_test_db_creation(cursor, parameters, verbosity)
except Exception, e:
except Exception as e:
sys.stderr.write("Got an error creating the test database: %s\n" % e)
if not autoclobber:
confirm = raw_input("It appears the test database, %s, already exists. Type 'yes' to delete it, or 'no' to cancel: " % TEST_NAME)
@ -72,7 +72,7 @@ class DatabaseCreation(BaseDatabaseCreation):
print "Destroying old test database '%s'..." % self.connection.alias
self._execute_test_db_destruction(cursor, parameters, verbosity)
self._execute_test_db_creation(cursor, parameters, verbosity)
except Exception, e:
except Exception as e:
sys.stderr.write("Got an error recreating the test database: %s\n" % e)
sys.exit(2)
else:
@ -84,7 +84,7 @@ class DatabaseCreation(BaseDatabaseCreation):
print "Creating test user..."
try:
self._create_test_user(cursor, parameters, verbosity)
except Exception, e:
except Exception as e:
sys.stderr.write("Got an error creating the test user: %s\n" % e)
if not autoclobber:
confirm = raw_input("It appears the test user, %s, already exists. Type 'yes' to delete it, or 'no' to cancel: " % TEST_USER)
@ -96,7 +96,7 @@ class DatabaseCreation(BaseDatabaseCreation):
if verbosity >= 1:
print "Creating test user..."
self._create_test_user(cursor, parameters, verbosity)
except Exception, e:
except Exception as e:
sys.stderr.write("Got an error recreating the test user: %s\n" % e)
sys.exit(2)
else:
@ -197,7 +197,7 @@ class DatabaseCreation(BaseDatabaseCreation):
print stmt
try:
cursor.execute(stmt)
except Exception, err:
except Exception as err:
sys.stderr.write("Failed (%s)\n" % (err))
raise

View File

@ -20,7 +20,7 @@ from django.utils.timezone import utc
try:
import psycopg2 as Database
import psycopg2.extensions
except ImportError, e:
except ImportError as e:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e)
@ -50,17 +50,17 @@ class CursorWrapper(object):
def execute(self, query, args=None):
try:
return self.cursor.execute(query, args)
except Database.IntegrityError, e:
except Database.IntegrityError as e:
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
except Database.DatabaseError, e:
except Database.DatabaseError as e:
raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
def executemany(self, query, args):
try:
return self.cursor.executemany(query, args)
except Database.IntegrityError, e:
except Database.IntegrityError as e:
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
except Database.DatabaseError, e:
except Database.DatabaseError as e:
raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
def __getattr__(self, attr):
@ -233,5 +233,5 @@ class DatabaseWrapper(BaseDatabaseWrapper):
if self.connection is not None:
try:
return self.connection.commit()
except Database.IntegrityError, e:
except Database.IntegrityError as e:
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]

View File

@ -24,9 +24,9 @@ from django.utils import timezone
try:
try:
from pysqlite2 import dbapi2 as Database
except ImportError, e1:
except ImportError:
from sqlite3 import dbapi2 as Database
except ImportError, exc:
except ImportError as exc:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured("Error loading either pysqlite2 or sqlite3 modules (tried in that order): %s" % exc)
@ -335,18 +335,18 @@ class SQLiteCursorWrapper(Database.Cursor):
query = self.convert_query(query)
try:
return Database.Cursor.execute(self, query, params)
except Database.IntegrityError, e:
except Database.IntegrityError as e:
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
except Database.DatabaseError, e:
except Database.DatabaseError as e:
raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
def executemany(self, query, param_list):
query = self.convert_query(query)
try:
return Database.Cursor.executemany(self, query, param_list)
except Database.IntegrityError, e:
except Database.IntegrityError as e:
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
except Database.DatabaseError, e:
except Database.DatabaseError as e:
raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
def convert_query(self, query):

View File

@ -57,7 +57,7 @@ class DatabaseCreation(BaseDatabaseCreation):
if autoclobber or confirm == 'yes':
try:
os.remove(test_database_name)
except Exception, e:
except Exception as e:
sys.stderr.write("Got an error deleting the old test database: %s\n" % e)
sys.exit(2)
else:

View File

@ -805,14 +805,14 @@ class Model(object):
try:
self.clean_fields(exclude=exclude)
except ValidationError, e:
except ValidationError as e:
errors = e.update_error_dict(errors)
# Form.clean() is run even if other validation fails, so do the
# same with Model.clean() for consistency.
try:
self.clean()
except ValidationError, e:
except ValidationError as e:
errors = e.update_error_dict(errors)
# Run unique checks, but only for fields that passed validation.
@ -821,7 +821,7 @@ class Model(object):
exclude.append(name)
try:
self.validate_unique(exclude=exclude)
except ValidationError, e:
except ValidationError as e:
errors = e.update_error_dict(errors)
if errors:
@ -846,7 +846,7 @@ class Model(object):
continue
try:
setattr(self, f.attname, f.clean(raw_value, self))
except ValidationError, e:
except ValidationError as e:
errors[f.name] = e.messages
if errors:

View File

@ -147,7 +147,7 @@ class Field(object):
for v in self.validators:
try:
v(value)
except exceptions.ValidationError, e:
except exceptions.ValidationError as e:
if hasattr(e, 'code') and e.code in self.error_messages:
message = self.error_messages[e.code]
if e.params:

View File

@ -206,7 +206,7 @@ class QuerySet(object):
qs = self._clone()
qs.query.set_limits(k, k + 1)
return list(qs)[0]
except self.model.DoesNotExist, e:
except self.model.DoesNotExist as e:
raise IndexError(e.args)
def __and__(self, other):
@ -454,7 +454,7 @@ class QuerySet(object):
obj.save(force_insert=True, using=self.db)
transaction.savepoint_commit(sid, using=self.db)
return obj, True
except IntegrityError, e:
except IntegrityError as e:
transaction.savepoint_rollback(sid, using=self.db)
exc_info = sys.exc_info()
try:

View File

@ -1112,7 +1112,7 @@ class Query(object):
parts, opts, alias, True, allow_many, allow_explicit_fk=True,
can_reuse=can_reuse, negate=negate,
process_extras=process_extras)
except MultiJoin, e:
except MultiJoin as e:
self.split_exclude(filter_expr, LOOKUP_SEP.join(parts[:e.level]),
can_reuse)
return

View File

@ -22,7 +22,7 @@ def load_backend(backend_name):
# Look for a fully qualified database backend name
try:
return import_module('.base', backend_name)
except ImportError, e_user:
except ImportError as e_user:
# The database backend wasn't found. Display a helpful error message
# listing all possible (built-in) database backends.
backend_dir = os.path.join(os.path.dirname(__file__), 'backends')
@ -112,7 +112,7 @@ class ConnectionRouter(object):
try:
module_name, klass_name = r.rsplit('.', 1)
module = import_module(module_name)
except ImportError, e:
except ImportError as e:
raise ImproperlyConfigured('Error importing database router %s: "%s"' % (klass_name, e))
try:
router_class = getattr(module, klass_name)

View File

@ -205,7 +205,7 @@ class Signal(object):
for receiver in self._live_receivers(_make_id(sender)):
try:
response = receiver(signal=self, sender=sender, **named)
except Exception, err:
except Exception as err:
responses.append((receiver, err))
else:
responses.append((receiver, response))

View File

@ -119,10 +119,10 @@ class BoundMethodWeakref(object):
try:
if callable( function ):
function( self )
except Exception, e:
except Exception as e:
try:
traceback.print_exc()
except AttributeError, err:
except AttributeError as err:
print '''Exception during saferef %s cleanup function %s: %s'''%(
self, function, e
)

View File

@ -132,7 +132,7 @@ class Field(object):
for v in self.validators:
try:
v(value)
except ValidationError, e:
except ValidationError as e:
if hasattr(e, 'code') and e.code in self.error_messages:
message = self.error_messages[e.code]
if e.params:
@ -884,7 +884,7 @@ class MultiValueField(Field):
raise ValidationError(self.error_messages['required'])
try:
clean_data.append(field.clean(field_value))
except ValidationError, e:
except ValidationError as e:
# Collect all validation errors in a single list, which we'll
# raise at the end of clean(), rather than raising a single
# exception for the first error we encounter.

View File

@ -289,7 +289,7 @@ class BaseForm(StrAndUnicode):
if hasattr(self, 'clean_%s' % name):
value = getattr(self, 'clean_%s' % name)()
self.cleaned_data[name] = value
except ValidationError, e:
except ValidationError as e:
self._errors[name] = self.error_class(e.messages)
if name in self.cleaned_data:
del self.cleaned_data[name]
@ -297,7 +297,7 @@ class BaseForm(StrAndUnicode):
def _clean_form(self):
try:
self.cleaned_data = self.clean()
except ValidationError, e:
except ValidationError as e:
self._errors[NON_FIELD_ERRORS] = self.error_class(e.messages)
def _post_clean(self):

View File

@ -291,7 +291,7 @@ class BaseFormSet(StrAndUnicode):
# Give self.clean() a chance to do cross-form validation.
try:
self.clean()
except ValidationError, e:
except ValidationError as e:
self._non_form_errors = self.error_class(e.messages)
def clean(self):

View File

@ -324,13 +324,13 @@ class BaseModelForm(BaseForm):
# Clean the model instance's fields.
try:
self.instance.clean_fields(exclude=exclude)
except ValidationError, e:
except ValidationError as e:
self._update_errors(e.message_dict)
# Call the model instance's clean method.
try:
self.instance.clean()
except ValidationError, e:
except ValidationError as e:
self._update_errors({NON_FIELD_ERRORS: e.messages})
# Validate uniqueness if needed.
@ -345,7 +345,7 @@ class BaseModelForm(BaseForm):
exclude = self._get_validation_exclusions()
try:
self.instance.validate_unique(exclude=exclude)
except ValidationError, e:
except ValidationError as e:
self._update_errors(e.message_dict)
def save(self, commit=True):

View File

@ -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 File

@ -290,7 +290,7 @@ class HttpRequest(object):
raise Exception("You cannot access body after reading from request's data stream")
try:
self._body = self.read()
except IOError, e:
except IOError as e:
raise UnreadablePostError, e, sys.exc_traceback
self._stream = StringIO(self._body)
return self._body
@ -556,7 +556,7 @@ class HttpResponse(object):
if isinstance(value, unicode):
try:
value = value.encode('us-ascii')
except UnicodeError, e:
except UnicodeError as e:
e.reason += ', HTTP response headers must be in US-ASCII format'
raise
else:

View File

@ -196,7 +196,7 @@ class MultiPartParser(object):
# We only special-case base64 transfer encoding
try:
chunk = str(chunk).decode('base64')
except Exception, e:
except Exception as e:
# Since this is only a chunk, any error is an unfixable error.
raise MultiPartParserError("Could not decode base64 data: %r" % e)
@ -209,7 +209,7 @@ class MultiPartParser(object):
# If the chunk received by the handler is None, then don't continue.
break
except SkipFile, e:
except SkipFile:
# Just use up the rest of this file...
exhaust(field_stream)
else:
@ -218,7 +218,7 @@ class MultiPartParser(object):
else:
# If this is neither a FIELD or a FILE, just exhaust the stream.
exhaust(stream)
except StopUpload, e:
except StopUpload as e:
if not e.connection_reset:
exhaust(self._input_data)
else:

View File

@ -265,7 +265,7 @@ class Parser(object):
self.invalid_block_tag(token, command, parse_until)
try:
compiled_result = compile_func(self, token)
except TemplateSyntaxError, e:
except TemplateSyntaxError as e:
if not self.compile_function_error(token, e):
raise
self.extend_nodelist(nodelist, compiled_result, token)
@ -774,7 +774,7 @@ class Variable(object):
# GOTCHA: This will also catch any TypeError
# raised in the function itself.
current = settings.TEMPLATE_STRING_IF_INVALID # invalid method call
except Exception, e:
except Exception as e:
if getattr(e, 'silent_variable_failure', False):
current = settings.TEMPLATE_STRING_IF_INVALID
else:
@ -1237,7 +1237,7 @@ def import_library(taglib_module):
"""
try:
mod = import_module(taglib_module)
except ImportError, e:
except ImportError as e:
# If the ImportError is because the taglib submodule does not exist,
# that's not an error that should be raised. If the submodule exists
# and raised an ImportError on the attempt to load it, that we want

View File

@ -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 File

@ -72,7 +72,7 @@ class DebugNodeList(NodeList):
def render_node(self, node, context):
try:
return node.render(context)
except Exception, e:
except Exception as e:
if not hasattr(e, 'django_template_source'):
e.django_template_source = node.source
raise
@ -87,7 +87,7 @@ class DebugVariableNode(VariableNode):
output = force_unicode(output)
except UnicodeDecodeError:
return ''
except Exception, e:
except Exception as e:
if not hasattr(e, 'django_template_source'):
e.django_template_source = self.source
raise

View File

@ -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 File

@ -183,7 +183,7 @@ class ForNode(Node):
for node in self.nodelist_loop:
try:
nodelist.append(node.render(context))
except Exception, e:
except Exception as e:
if not hasattr(e, 'django_template_source'):
e.django_template_source = node.source
raise
@ -337,7 +337,7 @@ class SsiNode(Node):
try:
t = Template(output, name=filepath)
return t.render(context)
except TemplateSyntaxError, e:
except TemplateSyntaxError as e:
if settings.DEBUG:
return "[Included template had syntax error: %s]" % e
else:
@ -403,7 +403,7 @@ class URLNode(Node):
url = ''
try:
url = reverse(view_name, args=args, kwargs=kwargs, current_app=context.current_app)
except NoReverseMatch, e:
except NoReverseMatch as e:
if settings.SETTINGS_MODULE:
project_name = settings.SETTINGS_MODULE.split('.')[0]
try:
@ -1005,7 +1005,7 @@ def load(parser, token):
try:
taglib = bits[-1]
lib = get_library(taglib)
except InvalidTemplateLibrary, e:
except InvalidTemplateLibrary as e:
raise TemplateSyntaxError("'%s' is not a valid tag library: %s" %
(taglib, e))
else:
@ -1028,7 +1028,7 @@ def load(parser, token):
try:
lib = get_library(taglib)
parser.add_library(lib)
except InvalidTemplateLibrary, e:
except InvalidTemplateLibrary as e:
raise TemplateSyntaxError("'%s' is not a valid tag library: %s" %
(taglib, e))
return LoadNode()

View File

@ -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 File

@ -19,7 +19,7 @@ app_template_dirs = []
for app in settings.INSTALLED_APPS:
try:
mod = import_module(app)
except ImportError, e:
except ImportError as e:
raise ImproperlyConfigured('ImportError %s: %s' % (app, e.args[0]))
template_dir = os.path.join(os.path.dirname(mod.__file__), 'templates')
if os.path.isdir(template_dir):

View File

@ -1626,7 +1626,7 @@ class DebugRunner(DocTestRunner):
... {}, 'foo', 'foo.py', 0)
>>> try:
... runner.run(test)
... except UnexpectedException, failure:
... except UnexpectedException as failure:
... pass
>>> failure.test is test
@ -1654,7 +1654,7 @@ class DebugRunner(DocTestRunner):
>>> try:
... runner.run(test)
... except DocTestFailure, failure:
... except DocTestFailure as failure:
... pass
DocTestFailure objects provide access to the test:
@ -2164,7 +2164,7 @@ class DocTestCase(unittest.TestCase):
>>> case = DocTestCase(test)
>>> try:
... case.debug()
... except UnexpectedException, failure:
... except UnexpectedException as failure:
... pass
The UnexpectedException contains the test, the example, and
@ -2193,7 +2193,7 @@ class DocTestCase(unittest.TestCase):
>>> try:
... case.debug()
... except DocTestFailure, failure:
... except DocTestFailure as failure:
... pass
DocTestFailure objects provide access to the test:

View File

@ -378,7 +378,7 @@ class Client(RequestFactory):
try:
response = self.handler(environ)
except TemplateDoesNotExist, e:
except TemplateDoesNotExist as e:
# If the view raises an exception, Django will attempt to show
# the 500.html template. If that template is not available,
# we should ignore the error in favor of re-raising the

View File

@ -84,7 +84,7 @@ def restore_transaction_methods():
def assert_and_parse_html(self, html, user_msg, msg):
try:
dom = parse_html(html)
except HTMLParseError, e:
except HTMLParseError as e:
standardMsg = u'%s\n%s' % (msg, e.msg)
self.fail(self._formatMessage(user_msg, standardMsg))
return dom
@ -1035,7 +1035,7 @@ class LiveServerThread(threading.Thread):
try:
self.httpd = StoppableWSGIServer(
(self.host, port), QuietWSGIRequestHandler)
except WSGIServerException, e:
except WSGIServerException as e:
if (index + 1 < len(self.possible_ports) and
e.args[0].errno == errno.EADDRINUSE):
# This port is already in use, so we go on and try with
@ -1054,7 +1054,7 @@ class LiveServerThread(threading.Thread):
self.httpd.set_app(handler)
self.is_ready.set()
self.httpd.serve_forever()
except Exception, e:
except Exception as e:
self.error = e
self.is_ready.set()

View File

@ -9,7 +9,7 @@ if os.name == 'posix':
try:
if os.fork() > 0:
sys.exit(0) # kill off parent
except OSError, e:
except OSError as e:
sys.stderr.write("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror))
sys.exit(1)
os.setsid()
@ -20,7 +20,7 @@ if os.name == 'posix':
try:
if os.fork() > 0:
os._exit(0)
except OSError, e:
except OSError as e:
sys.stderr.write("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror))
os._exit(1)

View File

@ -89,7 +89,7 @@ def make_middleware_decorator(middleware_class):
return result
try:
response = view_func(request, *args, **kwargs)
except Exception, e:
except Exception as e:
if hasattr(middleware, 'process_exception'):
result = middleware.process_exception(request, e)
if result is not None:

View File

@ -297,21 +297,21 @@ class DictConfigurator(BaseConfigurator):
level = handler_config.get('level', None)
if level:
handler.setLevel(_checkLevel(level))
except StandardError, e:
except StandardError as e:
raise ValueError('Unable to configure handler '
'%r: %s' % (name, e))
loggers = config.get('loggers', EMPTY_DICT)
for name in loggers:
try:
self.configure_logger(name, loggers[name], True)
except StandardError, e:
except StandardError as e:
raise ValueError('Unable to configure logger '
'%r: %s' % (name, e))
root = config.get('root', None)
if root:
try:
self.configure_root(root, True)
except StandardError, e:
except StandardError as e:
raise ValueError('Unable to configure root '
'logger: %s' % e)
else:
@ -326,7 +326,7 @@ class DictConfigurator(BaseConfigurator):
try:
formatters[name] = self.configure_formatter(
formatters[name])
except StandardError, e:
except StandardError as e:
raise ValueError('Unable to configure '
'formatter %r: %s' % (name, e))
# Next, do filters - they don't refer to anything else, either
@ -334,7 +334,7 @@ class DictConfigurator(BaseConfigurator):
for name in filters:
try:
filters[name] = self.configure_filter(filters[name])
except StandardError, e:
except StandardError as e:
raise ValueError('Unable to configure '
'filter %r: %s' % (name, e))
@ -347,7 +347,7 @@ class DictConfigurator(BaseConfigurator):
handler = self.configure_handler(handlers[name])
handler.name = name
handlers[name] = handler
except StandardError, e:
except StandardError as e:
raise ValueError('Unable to configure handler '
'%r: %s' % (name, e))
# Next, do loggers - they refer to handlers and filters
@ -386,7 +386,7 @@ class DictConfigurator(BaseConfigurator):
existing.remove(name)
try:
self.configure_logger(name, loggers[name])
except StandardError, e:
except StandardError as e:
raise ValueError('Unable to configure logger '
'%r: %s' % (name, e))
@ -409,7 +409,7 @@ class DictConfigurator(BaseConfigurator):
if root:
try:
self.configure_root(root)
except StandardError, e:
except StandardError as e:
raise ValueError('Unable to configure root '
'logger: %s' % e)
finally:
@ -421,7 +421,7 @@ class DictConfigurator(BaseConfigurator):
factory = config['()'] # for use in exception handler
try:
result = self.configure_custom(config)
except TypeError, te:
except TypeError as te:
if "'format'" not in str(te):
raise
#Name of parameter changed from fmt to format.
@ -451,7 +451,7 @@ class DictConfigurator(BaseConfigurator):
for f in filters:
try:
filterer.addFilter(self.config['filters'][f])
except StandardError, e:
except StandardError as e:
raise ValueError('Unable to add filter %r: %s' % (f, e))
def configure_handler(self, config):
@ -460,7 +460,7 @@ class DictConfigurator(BaseConfigurator):
if formatter:
try:
formatter = self.config['formatters'][formatter]
except StandardError, e:
except StandardError as e:
raise ValueError('Unable to set formatter '
'%r: %s' % (formatter, e))
level = config.pop('level', None)
@ -477,7 +477,7 @@ class DictConfigurator(BaseConfigurator):
'target' in config:
try:
config['target'] = self.config['handlers'][config['target']]
except StandardError, e:
except StandardError as e:
raise ValueError('Unable to set target handler '
'%r: %s' % (config['target'], e))
elif issubclass(klass, logging.handlers.SMTPHandler) and\
@ -490,7 +490,7 @@ class DictConfigurator(BaseConfigurator):
kwargs = dict([(k, config[k]) for k in config if valid_ident(k)])
try:
result = factory(**kwargs)
except TypeError, te:
except TypeError as te:
if "'stream'" not in str(te):
raise
#The argument name changed from strm to stream
@ -512,7 +512,7 @@ class DictConfigurator(BaseConfigurator):
for h in handlers:
try:
logger.addHandler(self.config['handlers'][h])
except StandardError, e:
except StandardError as e:
raise ValueError('Unable to add handler %r: %s' % (h, e))
def common_logger_config(self, logger, config, incremental=False):

View File

@ -88,7 +88,7 @@ def force_unicode(s, encoding='utf-8', strings_only=False, errors='strict'):
# errors), so that if s is a SafeString, it ends up being a
# SafeUnicode at the end.
s = s.decode(encoding, errors)
except UnicodeDecodeError, e:
except UnicodeDecodeError as e:
if not isinstance(s, Exception):
raise DjangoUnicodeDecodeError(s, *e.args)
else:

View File

@ -77,7 +77,7 @@ def get_exception_reporter_filter(request):
modname, classname = modpath.rsplit('.', 1)
try:
mod = import_module(modname)
except ImportError, e:
except ImportError as e:
raise ImproperlyConfigured(
'Error importing default exception reporter filter %s: "%s"' % (modpath, e))
try:

View File

@ -72,7 +72,7 @@ Example::
try:
article.full_clean()
except ValidationError, e:
except ValidationError as e:
# Do something based on the errors contained in e.message_dict.
# Display them to a user, or handle them programatically.
@ -112,7 +112,7 @@ instead of to a specific field::
from django.core.exceptions import ValidationError, NON_FIELD_ERRORS
try:
article.full_clean()
except ValidationError, e:
except ValidationError as e:
non_field_errors = e.message_dict[NON_FIELD_ERRORS]
Finally, ``full_clean()`` will check any unique constraints on your model.

View File

@ -173,7 +173,7 @@ class Template(object):
fd = open(self.absolute_filename)
try:
content = fd.read().decode(TEMPLATE_ENCODING)
except UnicodeDecodeError, e:
except UnicodeDecodeError as e:
message = '%s in %s' % (
e[4], self.absolute_filename.encode('UTF-8', 'ignore'))
raise UnicodeDecodeError(*(e.args[:4] + (message,)))

View File

@ -384,9 +384,9 @@ class ModelTest(TestCase):
try:
Article.objects.all()[0:1] & Article.objects.all()[4:5]
self.fail('Should raise an AssertionError')
except AssertionError, e:
except AssertionError as e:
self.assertEqual(str(e), "Cannot combine queries once a slice has been taken.")
except Exception, e:
except Exception as e:
self.fail('Should raise an AssertionError, not %s' % e)
# Negative slices are not supported, due to database constraints.
@ -394,15 +394,15 @@ class ModelTest(TestCase):
try:
Article.objects.all()[-1]
self.fail('Should raise an AssertionError')
except AssertionError, e:
except AssertionError as e:
self.assertEqual(str(e), "Negative indexing is not supported.")
except Exception, e:
except Exception as e:
self.fail('Should raise an AssertionError, not %s' % e)
error = None
try:
Article.objects.all()[0:-5]
except Exception, e:
except Exception as e:
error = e
self.assertTrue(isinstance(error, AssertionError))
self.assertEqual(str(error), "Negative indexing is not supported.")

View File

@ -60,7 +60,7 @@ class GetOrCreateTests(TestCase):
# the actual traceback. Refs #16340.
try:
ManualPrimaryKeyTest.objects.get_or_create(id=1, data="Different")
except IntegrityError, e:
except IntegrityError as e:
formatted_traceback = traceback.format_exc()
self.assertIn('obj.save', formatted_traceback)

View File

@ -35,7 +35,7 @@ class InvalidModelTestCase(unittest.TestCase):
try:
module = load_app("modeltests.invalid_models.invalid_models")
except Exception, e:
except Exception:
self.fail('Unable to load invalid model module')
count = get_validation_errors(self.stdout, module)

View File

@ -468,13 +468,13 @@ class LookupTests(TestCase):
try:
Article.objects.filter(pub_date_year='2005').count()
self.fail('FieldError not raised')
except FieldError, ex:
except FieldError as ex:
self.assertEqual(str(ex), "Cannot resolve keyword 'pub_date_year' "
"into field. Choices are: author, headline, id, pub_date, tag")
try:
Article.objects.filter(headline__starts='Article')
self.fail('FieldError not raised')
except FieldError, ex:
except FieldError as ex:
self.assertEqual(str(ex), "Join on field 'headline' not permitted. "
"Did you misspell 'starts' for the lookup type?")

View File

@ -169,10 +169,8 @@ class SelectForUpdateTests(TransactionTestCase):
people[0].name = 'Fred'
people[0].save()
transaction.commit()
except DatabaseError, e:
except DatabaseError as e:
status.append(e)
except Exception, e:
raise
finally:
# This method is run in a separate thread. It uses its own
# database connection. Close it without waiting for the GC.
@ -246,7 +244,7 @@ class SelectForUpdateTests(TransactionTestCase):
)
)
)
except DatabaseError, e:
except DatabaseError as e:
status.append(e)
finally:
# This method is run in a separate thread. It uses its own

View File

@ -99,6 +99,6 @@ try:
class MultipleAutoFields(models.Model):
auto1 = models.AutoField(primary_key=True)
auto2 = models.AutoField(primary_key=True)
except AssertionError, assertion_error:
except AssertionError as assertion_error:
pass # Fail silently
assert str(assertion_error) == u"A model can't have more than one AutoField."

View File

@ -10,13 +10,13 @@ class ValidationMessagesTest(TestCase):
self.assertRaises(ValidationError, f.clean, 'foo', None)
try:
f.clean('foo', None)
except ValidationError, e:
except ValidationError as e:
self.assertEqual(e.messages, [u"'foo' value must be an integer."])
# primary_key must be True. Refs #12467.
self.assertRaises(AssertionError, models.AutoField, 'primary_key', False)
try:
models.AutoField(primary_key=False)
except AssertionError, e:
except AssertionError as e:
self.assertEqual(str(e), "AutoFields must have primary_key=True.")
def test_integer_field_raises_error_message(self):
@ -24,7 +24,7 @@ class ValidationMessagesTest(TestCase):
self.assertRaises(ValidationError, f.clean, 'foo', None)
try:
f.clean('foo', None)
except ValidationError, e:
except ValidationError as e:
self.assertEqual(e.messages, [u"'foo' value must be an integer."])
def test_boolean_field_raises_error_message(self):
@ -32,7 +32,7 @@ class ValidationMessagesTest(TestCase):
self.assertRaises(ValidationError, f.clean, 'foo', None)
try:
f.clean('foo', None)
except ValidationError, e:
except ValidationError as e:
self.assertEqual(e.messages,
[u"'foo' value must be either True or False."])
@ -41,7 +41,7 @@ class ValidationMessagesTest(TestCase):
self.assertRaises(ValidationError, f.clean, 'foo', None)
try:
f.clean('foo', None)
except ValidationError, e:
except ValidationError as e:
self.assertEqual(e.messages, [u"'foo' value must be a float."])
def test_decimal_field_raises_error_message(self):
@ -49,7 +49,7 @@ class ValidationMessagesTest(TestCase):
self.assertRaises(ValidationError, f.clean, 'foo', None)
try:
f.clean('foo', None)
except ValidationError, e:
except ValidationError as e:
self.assertEqual(e.messages,
[u"'foo' value must be a decimal number."])
@ -58,7 +58,7 @@ class ValidationMessagesTest(TestCase):
self.assertRaises(ValidationError, f.clean, 'foo', None)
try:
f.clean('foo', None)
except ValidationError, e:
except ValidationError as e:
self.assertEqual(e.messages,
[u"'foo' value must be either None, True or False."])
@ -67,7 +67,7 @@ class ValidationMessagesTest(TestCase):
self.assertRaises(ValidationError, f.clean, 'foo', None)
try:
f.clean('foo', None)
except ValidationError, e:
except ValidationError as e:
self.assertEqual(e.messages, [
u"'foo' value has an invalid date format. "
u"It must be in YYYY-MM-DD format."])
@ -75,7 +75,7 @@ class ValidationMessagesTest(TestCase):
self.assertRaises(ValidationError, f.clean, 'aaaa-10-10', None)
try:
f.clean('aaaa-10-10', None)
except ValidationError, e:
except ValidationError as e:
self.assertEqual(e.messages, [
u"'aaaa-10-10' value has an invalid date format. "
u"It must be in YYYY-MM-DD format."])
@ -83,7 +83,7 @@ class ValidationMessagesTest(TestCase):
self.assertRaises(ValidationError, f.clean, '2011-13-10', None)
try:
f.clean('2011-13-10', None)
except ValidationError, e:
except ValidationError as e:
self.assertEqual(e.messages, [
u"'2011-13-10' value has the correct format (YYYY-MM-DD) "
u"but it is an invalid date."])
@ -91,7 +91,7 @@ class ValidationMessagesTest(TestCase):
self.assertRaises(ValidationError, f.clean, '2011-10-32', None)
try:
f.clean('2011-10-32', None)
except ValidationError, e:
except ValidationError as e:
self.assertEqual(e.messages, [
u"'2011-10-32' value has the correct format (YYYY-MM-DD) "
u"but it is an invalid date."])
@ -102,7 +102,7 @@ class ValidationMessagesTest(TestCase):
self.assertRaises(ValidationError, f.clean, 'foo', None)
try:
f.clean('foo', None)
except ValidationError, e:
except ValidationError as e:
self.assertEqual(e.messages, [
u"'foo' value has an invalid format. It must be "
u"in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."])
@ -111,7 +111,7 @@ class ValidationMessagesTest(TestCase):
self.assertRaises(ValidationError, f.clean, '2011-10-32', None)
try:
f.clean('2011-10-32', None)
except ValidationError, e:
except ValidationError as e:
self.assertEqual(e.messages, [
u"'2011-10-32' value has the correct format "
u"(YYYY-MM-DD) but it is an invalid date."])
@ -120,7 +120,7 @@ class ValidationMessagesTest(TestCase):
self.assertRaises(ValidationError, f.clean, '2011-10-32 10:10', None)
try:
f.clean('2011-10-32 10:10', None)
except ValidationError, e:
except ValidationError as e:
self.assertEqual(e.messages, [
u"'2011-10-32 10:10' value has the correct format "
u"(YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) "
@ -132,7 +132,7 @@ class ValidationMessagesTest(TestCase):
self.assertRaises(ValidationError, f.clean, 'foo', None)
try:
f.clean('foo', None)
except ValidationError, e:
except ValidationError as e:
self.assertEqual(e.messages, [
u"'foo' value has an invalid format. It must be in "
u"HH:MM[:ss[.uuuuuu]] format."])
@ -140,7 +140,7 @@ class ValidationMessagesTest(TestCase):
self.assertRaises(ValidationError, f.clean, '25:50', None)
try:
f.clean('25:50', None)
except ValidationError, e:
except ValidationError as e:
self.assertEqual(e.messages, [
u"'25:50' value has the correct format "
u"(HH:MM[:ss[.uuuuuu]]) but it is an invalid time."])

View File

@ -115,19 +115,19 @@ class PerformUniqueChecksTest(TestCase):
p = FlexibleDatePost(title="Django 1.0 is released")
try:
p.full_clean()
except ValidationError, e:
except ValidationError:
self.fail("unique_for_date checks shouldn't trigger when the associated DateField is None.")
p = FlexibleDatePost(slug="Django 1.0")
try:
p.full_clean()
except ValidationError, e:
except ValidationError:
self.fail("unique_for_year checks shouldn't trigger when the associated DateField is None.")
p = FlexibleDatePost(subtitle="Finally")
try:
p.full_clean()
except ValidationError, e:
except ValidationError:
self.fail("unique_for_month checks shouldn't trigger when the associated DateField is None.")
def test_unique_errors(self):

View File

@ -61,7 +61,7 @@ class EggLoadingTest(TestCase):
self.assertRaises(ImportError, load_app, 'broken_app')
try:
load_app('broken_app')
except ImportError, e:
except ImportError as e:
# Make sure the message is indicating the actual
# problem in the broken app.
self.assertTrue("modelz" in e.args[0])

View File

@ -569,7 +569,7 @@ class ThreadTests(TestCase):
connections['default'] = main_thread_connection
try:
models.Person.objects.get(first_name="John", last_name="Doe")
except DatabaseError, e:
except DatabaseError as e:
exceptions.append(e)
t = threading.Thread(target=runner, args=[connections['default']])
t.start()
@ -607,7 +607,7 @@ class ThreadTests(TestCase):
def runner2(other_thread_connection):
try:
other_thread_connection.close()
except DatabaseError, e:
except DatabaseError as e:
exceptions.add(e)
t2 = threading.Thread(target=runner2, args=[connections['default']])
t2.start()
@ -624,7 +624,7 @@ class ThreadTests(TestCase):
def runner2(other_thread_connection):
try:
other_thread_connection.close()
except DatabaseError, e:
except DatabaseError as e:
exceptions.add(e)
# Enable thread sharing
connections['default'].allow_thread_sharing = True

View File

@ -304,7 +304,7 @@ class FileUploadTests(TestCase):
# it raises when there is an attempt to read more than the available bytes:
try:
client.FakePayload('a').read(2)
except Exception, reference_error:
except Exception as reference_error:
pass
# install the custom handler that tries to access request.POST
@ -312,12 +312,12 @@ class FileUploadTests(TestCase):
try:
response = self.client.post('/file_uploads/upload_errors/', post_data)
except reference_error.__class__, err:
except reference_error.__class__ as err:
self.failIf(
str(err) == str(reference_error),
"Caught a repeated exception that'll cause an infinite loop in file uploads."
)
except Exception, err:
except Exception as err:
# CustomUploadError is the error that should have been raised
self.assertEqual(err.__class__, uploadhandler.CustomUploadError)
@ -374,9 +374,9 @@ class DirectoryCreationTests(unittest.TestCase):
os.chmod(temp_storage.location, 0500)
try:
self.obj.testfile.save('foo.txt', SimpleUploadedFile('foo.txt', 'x'))
except OSError, err:
except OSError as err:
self.assertEqual(err.errno, errno.EACCES)
except Exception, err:
except Exception:
self.fail("OSError [Errno %s] not raised." % errno.EACCES)
def test_not_a_directory(self):
@ -386,7 +386,7 @@ class DirectoryCreationTests(unittest.TestCase):
fd.close()
try:
self.obj.testfile.save('foo.txt', SimpleUploadedFile('foo.txt', 'x'))
except IOError, err:
except IOError as err:
# The test needs to be done on a specific string as IOError
# is raised even without the patch (just not early enough)
self.assertEqual(err.args[0],

View File

@ -13,7 +13,7 @@ class AssertFormErrorsMixin(object):
try:
the_callable(*args, **kwargs)
self.fail("Testing the 'clean' method on %s failed to raise a ValidationError.")
except ValidationError, e:
except ValidationError as e:
self.assertEqual(e.messages, expected)
class FormsErrorMessagesTestCase(TestCase, AssertFormErrorsMixin):

View File

@ -12,5 +12,5 @@ class TestFieldWithValidators(TestCase):
self.assertRaises(ValidationError, field.clean, 'not int nor mail')
try:
field.clean('not int nor mail')
except ValidationError, e:
except ValidationError as e:
self.assertEqual(2, len(e.messages))

View File

@ -88,7 +88,7 @@ class CommonMiddlewareTest(TestCase):
request)
try:
CommonMiddleware().process_request(request)
except RuntimeError, e:
except RuntimeError as e:
self.assertTrue('end in a slash' in str(e))
settings.DEBUG = False
@ -202,7 +202,7 @@ class CommonMiddlewareTest(TestCase):
request)
try:
CommonMiddleware().process_request(request)
except RuntimeError, e:
except RuntimeError as e:
self.assertTrue('end in a slash' in str(e))
settings.DEBUG = False

View File

@ -118,13 +118,13 @@ class BaseMiddlewareExceptionTest(TestCase):
def assert_exceptions_handled(self, url, errors, extra_error=None):
try:
response = self.client.get(url)
except TestException, e:
except TestException:
# Test client intentionally re-raises any exceptions being raised
# during request handling. Hence actual testing that exception was
# properly handled is done by relying on got_request_exception
# signal being sent.
pass
except Exception, e:
except Exception as e:
if type(extra_error) != type(e):
self.fail("Unexpected exception: %s" % e)
self.assertEqual(len(self.exceptions), len(errors))

View File

@ -44,7 +44,7 @@ class BasicFieldTests(test.TestCase):
nullboolean = NullBooleanModel(nbfield=None)
try:
nullboolean.full_clean()
except ValidationError, e:
except ValidationError as e:
self.fail("NullBooleanField failed validation with value of None: %s" % e.messages)
def test_field_repr(self):

Some files were not shown because too many files have changed in this diff Show More