1
0
mirror of https://github.com/django/django.git synced 2025-11-07 07:15:35 +00:00

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

@@ -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'@')