diff options
| author | Claude Paroz <claude@2xlibre.net> | 2012-04-28 18:09:37 +0200 |
|---|---|---|
| committer | Claude Paroz <claude@2xlibre.net> | 2012-04-29 20:57:15 +0200 |
| commit | 3904b74a3f2f92fefe1d39281ed683c52f2fef03 (patch) | |
| tree | 1ae8f65371ed53df205553f41c9d0f90d1e9fee9 /django/core | |
| parent | eefb00f30124f775ca52258ccd8549054fe8230f (diff) | |
Fixed #18013 -- Use the new 'as' syntax for exceptions.
Thanks Clueless for the initial patch.
Note that unittest has been purposely left out (external package only used by Python 2.6).
Diffstat (limited to 'django/core')
24 files changed, 44 insertions, 43 deletions
diff --git a/django/core/cache/__init__.py b/django/core/cache/__init__.py index 8f07f13d3a..2a9e1a700b 100644 --- a/django/core/cache/__init__.py +++ b/django/core/cache/__init__.py @@ -128,7 +128,7 @@ def get_cache(backend, **kwargs): mod_path, cls_name = backend.rsplit('.', 1) mod = importlib.import_module(mod_path) backend_cls = getattr(mod, cls_name) - except (AttributeError, ImportError), e: + except (AttributeError, ImportError) as e: raise InvalidCacheBackendError( "Could not find backend '%s': %s" % (backend, e)) cache = backend_cls(location, params) diff --git a/django/core/files/move.py b/django/core/files/move.py index 3349fc22e7..4778228ccd 100644 --- a/django/core/files/move.py +++ b/django/core/files/move.py @@ -79,7 +79,7 @@ def file_move_safe(old_file_name, new_file_name, chunk_size = 1024*64, allow_ove try: os.remove(old_file_name) - except OSError, e: + except OSError as e: # Certain operating systems (Cygwin and Windows) # fail when deleting opened files, ignore it. (For the # systems where this happens, temporary files will be auto-deleted diff --git a/django/core/files/storage.py b/django/core/files/storage.py index aa62175819..6b724b4028 100644 --- a/django/core/files/storage.py +++ b/django/core/files/storage.py @@ -166,7 +166,7 @@ class FileSystemStorage(Storage): if not os.path.exists(directory): try: os.makedirs(directory) - except OSError, e: + except OSError as e: if e.errno != errno.EEXIST: raise if not os.path.isdir(directory): @@ -197,7 +197,7 @@ class FileSystemStorage(Storage): finally: locks.unlock(fd) os.close(fd) - except OSError, e: + except OSError as e: if e.errno == errno.EEXIST: # Ooops, the file exists. We need a new file name. name = self.get_available_name(name) @@ -222,7 +222,7 @@ class FileSystemStorage(Storage): if os.path.exists(name): try: os.remove(name) - except OSError, e: + except OSError as e: if e.errno != errno.ENOENT: raise @@ -273,7 +273,7 @@ def get_storage_class(import_path=None): module, classname = import_path[:dot], import_path[dot+1:] try: mod = import_module(module) - except ImportError, e: + except ImportError as e: raise ImproperlyConfigured('Error importing storage module %s: "%s"' % (module, e)) try: return getattr(mod, classname) diff --git a/django/core/files/uploadedfile.py b/django/core/files/uploadedfile.py index 5178f0bacc..1dcd9aeeb0 100644 --- a/django/core/files/uploadedfile.py +++ b/django/core/files/uploadedfile.py @@ -75,7 +75,7 @@ class TemporaryUploadedFile(UploadedFile): def close(self): try: return self.file.close() - except OSError, e: + except OSError as e: if e.errno != 2: # Means the file was moved or deleted before the tempfile # could unlink it. Still sets self.file.close_called and diff --git a/django/core/files/uploadhandler.py b/django/core/files/uploadhandler.py index 2afb79e051..4316fddf43 100644 --- a/django/core/files/uploadhandler.py +++ b/django/core/files/uploadhandler.py @@ -204,10 +204,11 @@ def load_handler(path, *args, **kwargs): module, attr = path[:i], path[i+1:] try: mod = importlib.import_module(module) - except ImportError, e: + except ImportError as e: raise ImproperlyConfigured('Error importing upload handler module %s: "%s"' % (module, e)) - except ValueError, e: - raise ImproperlyConfigured('Error importing upload handler module. Is FILE_UPLOAD_HANDLERS a correctly defined list or tuple?') + except ValueError: + raise ImproperlyConfigured('Error importing upload handler module.' + 'Is FILE_UPLOAD_HANDLERS a correctly defined list or tuple?') try: cls = getattr(mod, attr) except AttributeError: diff --git a/django/core/handlers/base.py b/django/core/handlers/base.py index a0918bfc41..4c9dfc07bc 100644 --- a/django/core/handlers/base.py +++ b/django/core/handlers/base.py @@ -43,7 +43,7 @@ class BaseHandler(object): raise exceptions.ImproperlyConfigured('%s isn\'t a middleware module' % middleware_path) try: mod = import_module(mw_module) - except ImportError, e: + except ImportError as e: raise exceptions.ImproperlyConfigured('Error importing middleware %s: "%s"' % (mw_module, e)) try: mw_class = getattr(mod, mw_classname) @@ -109,7 +109,7 @@ class BaseHandler(object): if response is None: try: response = callback(request, *callback_args, **callback_kwargs) - except Exception, e: + except Exception as e: # If the view raised an exception, run it through exception # middleware, and if the exception middleware returns a # response, use that. Otherwise, reraise the exception. @@ -135,7 +135,7 @@ class BaseHandler(object): response = middleware_method(request, response) response = response.render() - except http.Http404, e: + except http.Http404 as e: logger.warning('Not Found: %s', request.path, extra={ 'status_code': 404, diff --git a/django/core/mail/__init__.py b/django/core/mail/__init__.py index a9b651e538..1bee0cac9f 100644 --- a/django/core/mail/__init__.py +++ b/django/core/mail/__init__.py @@ -30,7 +30,7 @@ def get_connection(backend=None, fail_silently=False, **kwds): try: mod_name, klass_name = path.rsplit('.', 1) mod = import_module(mod_name) - except ImportError, e: + except ImportError as e: raise ImproperlyConfigured(('Error importing email backend module %s: "%s"' % (mod_name, e))) try: diff --git a/django/core/mail/backends/filebased.py b/django/core/mail/backends/filebased.py index 3f6b99b057..674ca32f3f 100644 --- a/django/core/mail/backends/filebased.py +++ b/django/core/mail/backends/filebased.py @@ -25,7 +25,7 @@ class EmailBackend(ConsoleEmailBackend): elif not os.path.exists(self.file_path): try: os.makedirs(self.file_path) - except OSError, err: + except OSError as err: raise ImproperlyConfigured('Could not create directory for saving email messages: %s (%s)' % (self.file_path, err)) # Make sure that self.file_path is writable. if not os.access(self.file_path, os.W_OK): diff --git a/django/core/management/__init__.py b/django/core/management/__init__.py index 8f32898834..840a3b74df 100644 --- a/django/core/management/__init__.py +++ b/django/core/management/__init__.py @@ -51,7 +51,7 @@ def find_management_module(app_name): # of the app_name but the project directory itself isn't on the path. try: f, path, descr = imp.find_module(part,path) - except ImportError,e: + except ImportError as e: if os.path.basename(os.getcwd()) != part: raise e diff --git a/django/core/management/base.py b/django/core/management/base.py index 0bd64f24b5..2a04c25228 100644 --- a/django/core/management/base.py +++ b/django/core/management/base.py @@ -214,7 +214,7 @@ class BaseCommand(object): from django.utils import translation saved_lang = translation.get_language() translation.activate('en-us') - except ImportError, e: + except ImportError as e: # If settings should be available, but aren't, # raise the error and quit. if show_traceback: @@ -240,7 +240,7 @@ class BaseCommand(object): self.stdout.write(output) if self.output_transaction: self.stdout.write('\n' + self.style.SQL_KEYWORD("COMMIT;") + '\n') - except CommandError, e: + except CommandError as e: if show_traceback: traceback.print_exc() else: @@ -297,7 +297,7 @@ class AppCommand(BaseCommand): raise CommandError('Enter at least one appname.') try: app_list = [models.get_app(app_label) for app_label in app_labels] - except (ImproperlyConfigured, ImportError), e: + except (ImproperlyConfigured, ImportError) as e: raise CommandError("%s. Are you sure your INSTALLED_APPS setting is correct?" % e) output = [] for app in app_list: diff --git a/django/core/management/commands/createcachetable.py b/django/core/management/commands/createcachetable.py index 7164d1aa76..82a126b0fa 100644 --- a/django/core/management/commands/createcachetable.py +++ b/django/core/management/commands/createcachetable.py @@ -54,7 +54,7 @@ class Command(LabelCommand): curs = connection.cursor() try: curs.execute("\n".join(full_statement)) - except DatabaseError, e: + except DatabaseError as e: self.stderr.write( self.style.ERROR("Cache table '%s' could not be created.\nThe error was: %s.\n" % (tablename, e))) diff --git a/django/core/management/commands/dumpdata.py b/django/core/management/commands/dumpdata.py index 1622929e93..71d6fa74f1 100644 --- a/django/core/management/commands/dumpdata.py +++ b/django/core/management/commands/dumpdata.py @@ -111,7 +111,7 @@ class Command(BaseCommand): try: return serializers.serialize(format, objects, indent=indent, use_natural_keys=use_natural_keys) - except Exception, e: + except Exception as e: if show_traceback: raise raise CommandError("Unable to serialize database: %s" % e) diff --git a/django/core/management/commands/flush.py b/django/core/management/commands/flush.py index 2e936840ff..ce3c6e856b 100644 --- a/django/core/management/commands/flush.py +++ b/django/core/management/commands/flush.py @@ -55,7 +55,7 @@ Are you sure you want to do this? cursor = connection.cursor() for sql in sql_list: cursor.execute(sql) - except Exception, e: + except Exception as e: transaction.rollback_unless_managed(using=db) raise CommandError("""Database %s couldn't be flushed. Possible reasons: * The database isn't running or isn't configured correctly. diff --git a/django/core/management/commands/loaddata.py b/django/core/management/commands/loaddata.py index 2f1775e271..848b63705a 100644 --- a/django/core/management/commands/loaddata.py +++ b/django/core/management/commands/loaddata.py @@ -190,7 +190,7 @@ class Command(BaseCommand): models.add(obj.object.__class__) try: obj.save(using=using) - except (DatabaseError, IntegrityError), e: + except (DatabaseError, IntegrityError) as e: msg = "Could not load %(app_label)s.%(object_name)s(pk=%(pk)s): %(error_msg)s" % { 'app_label': obj.object._meta.app_label, 'object_name': obj.object._meta.object_name, diff --git a/django/core/management/commands/runserver.py b/django/core/management/commands/runserver.py index 3007d0fd30..e6182198ec 100644 --- a/django/core/management/commands/runserver.py +++ b/django/core/management/commands/runserver.py @@ -109,7 +109,7 @@ class Command(BaseCommand): handler = self.get_handler(*args, **options) run(self.addr, int(self.port), handler, ipv6=self.use_ipv6, threading=threading) - except WSGIServerException, e: + except WSGIServerException as e: # Use helpful error messages instead of ugly tracebacks. ERRORS = { 13: "You don't have permission to access that port.", diff --git a/django/core/management/commands/syncdb.py b/django/core/management/commands/syncdb.py index b04ba4b47f..91f0aeca30 100644 --- a/django/core/management/commands/syncdb.py +++ b/django/core/management/commands/syncdb.py @@ -37,7 +37,7 @@ class Command(NoArgsCommand): for app_name in settings.INSTALLED_APPS: try: import_module('.management', app_name) - except ImportError, exc: + except ImportError as exc: # This is slightly hackish. We want to ignore ImportErrors # if the "management" module itself is missing -- but we don't # want to ignore the exception if the management module exists @@ -125,7 +125,7 @@ class Command(NoArgsCommand): try: for sql in custom_sql: cursor.execute(sql) - except Exception, e: + except Exception as e: self.stderr.write("Failed to install custom SQL for %s.%s model: %s\n" % \ (app_name, model._meta.object_name, e)) if show_traceback: @@ -150,7 +150,7 @@ class Command(NoArgsCommand): try: for sql in index_sql: cursor.execute(sql) - except Exception, e: + except Exception as e: self.stderr.write("Failed to install index for %s.%s model: %s\n" % \ (app_name, model._meta.object_name, e)) transaction.rollback_unless_managed(using=db) diff --git a/django/core/management/templates.py b/django/core/management/templates.py index b2a1226dbc..735e29ad7f 100644 --- a/django/core/management/templates.py +++ b/django/core/management/templates.py @@ -81,7 +81,7 @@ class TemplateCommand(BaseCommand): top_dir = path.join(os.getcwd(), name) try: os.makedirs(top_dir) - except OSError, e: + except OSError as e: if e.errno == errno.EEXIST: message = "'%s' already exists" % top_dir else: @@ -231,7 +231,7 @@ class TemplateCommand(BaseCommand): try: the_path, info = urllib.urlretrieve(url, path.join(tempdir, filename)) - except IOError, e: + except IOError as e: raise CommandError("couldn't download URL %s to %s: %s" % (url, filename, e)) @@ -286,7 +286,7 @@ class TemplateCommand(BaseCommand): try: archive.extract(filename, tempdir) return tempdir - except (archive.ArchiveException, IOError), e: + except (archive.ArchiveException, IOError) as e: raise CommandError("couldn't extract file %s to %s: %s" % (filename, tempdir, e)) diff --git a/django/core/serializers/json.py b/django/core/serializers/json.py index ab0cd0e590..eb9fcfbacd 100644 --- a/django/core/serializers/json.py +++ b/django/core/serializers/json.py @@ -45,7 +45,7 @@ def Deserializer(stream_or_string, **options): yield obj except GeneratorExit: raise - except Exception, e: + except Exception as e: # Map to deserializer error raise DeserializationError(e) diff --git a/django/core/serializers/pyyaml.py b/django/core/serializers/pyyaml.py index 7a508da5d7..dc884a66c7 100644 --- a/django/core/serializers/pyyaml.py +++ b/django/core/serializers/pyyaml.py @@ -57,6 +57,6 @@ def Deserializer(stream_or_string, **options): yield obj except GeneratorExit: raise - except Exception, e: + except Exception as e: # Map to deserializer error raise DeserializationError(e) diff --git a/django/core/servers/basehttp.py b/django/core/servers/basehttp.py index d538ce70e8..82c5aca149 100644 --- a/django/core/servers/basehttp.py +++ b/django/core/servers/basehttp.py @@ -48,13 +48,13 @@ def get_internal_wsgi_application(): module_name, attr = app_path.rsplit('.', 1) try: mod = import_module(module_name) - except ImportError, e: + except ImportError as e: raise ImproperlyConfigured( "WSGI application '%s' could not be loaded; " "could not import module '%s': %s" % (app_path, module_name, e)) try: app = getattr(mod, attr) - except AttributeError, e: + except AttributeError as e: raise ImproperlyConfigured( "WSGI application '%s' could not be loaded; " "can't find '%s' in module '%s': %s" @@ -118,7 +118,7 @@ class WSGIServer(simple_server.WSGIServer, object): """Override server_bind to store the server name.""" try: super(WSGIServer, self).server_bind() - except Exception, e: + except Exception as e: raise WSGIServerException(e) self.setup_environ() diff --git a/django/core/servers/fastcgi.py b/django/core/servers/fastcgi.py index 17fd609fa7..9c652a74ef 100644 --- a/django/core/servers/fastcgi.py +++ b/django/core/servers/fastcgi.py @@ -102,7 +102,7 @@ def runfastcgi(argset=[], **kwargs): try: import flup - except ImportError, e: + except ImportError as e: print >> sys.stderr, "ERROR: %s" % e print >> sys.stderr, " Unable to load the flup package. In order to run django" print >> sys.stderr, " as a FastCGI application, you will need to get flup from" diff --git a/django/core/signing.py b/django/core/signing.py index f2c79de706..cd9759e536 100644 --- a/django/core/signing.py +++ b/django/core/signing.py @@ -77,12 +77,12 @@ def get_cookie_signer(salt='django.core.signing.get_cookie_signer'): module, attr = modpath.rsplit('.', 1) try: mod = import_module(module) - except ImportError, e: + except ImportError as e: raise ImproperlyConfigured( 'Error importing cookie signer %s: "%s"' % (modpath, e)) try: Signer = getattr(mod, attr) - except AttributeError, e: + except AttributeError as e: raise ImproperlyConfigured( 'Error importing cookie signer %s: "%s"' % (modpath, e)) return Signer('django.http.cookies' + settings.SECRET_KEY, salt=salt) diff --git a/django/core/urlresolvers.py b/django/core/urlresolvers.py index 1497d43e91..aadd290c33 100644 --- a/django/core/urlresolvers.py +++ b/django/core/urlresolvers.py @@ -298,7 +298,7 @@ class RegexURLResolver(LocaleRegexProvider): for pattern in self.url_patterns: try: sub_match = pattern.resolve(new_path) - except Resolver404, e: + except Resolver404 as e: sub_tried = e.args[0].get('tried') if sub_tried is not None: tried.extend([[pattern] + t for t in sub_tried]) @@ -358,7 +358,7 @@ class RegexURLResolver(LocaleRegexProvider): raise ValueError("Don't mix *args and **kwargs in call to reverse()!") try: lookup_view = get_callable(lookup_view, True) - except (ImportError, AttributeError), e: + except (ImportError, AttributeError) as e: raise NoReverseMatch("Error importing '%s': %s." % (lookup_view, e)) possibilities = self.reverse_dict.getlist(lookup_view) prefix_norm, prefix_args = normalize(_prefix)[0] @@ -462,7 +462,7 @@ def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None, current extra, resolver = resolver.namespace_dict[ns] resolved_path.append(ns) ns_pattern = ns_pattern + extra - except KeyError, key: + except KeyError as key: if resolved_path: raise NoReverseMatch( "%s is not a registered namespace inside '%s'" % diff --git a/django/core/validators.py b/django/core/validators.py index ce8e6937fe..3d4bcc86c8 100644 --- a/django/core/validators.py +++ b/django/core/validators.py @@ -45,7 +45,7 @@ class URLValidator(RegexValidator): def __call__(self, value): try: super(URLValidator, self).__call__(value) - except ValidationError, e: + except ValidationError as e: # Trivial case failed. Try for possible IDN domain if value: value = smart_unicode(value) @@ -73,7 +73,7 @@ class EmailValidator(RegexValidator): def __call__(self, value): try: super(EmailValidator, self).__call__(value) - except ValidationError, e: + except ValidationError as e: # Trivial case failed. Try for possible IDN domain-part if value and u'@' in value: parts = value.split(u'@') |
