ditch the old "except Exception, e" syntax

This commit is contained in:
Stefan Wojcik 2016-12-05 23:23:38 -05:00
parent 25e0f12976
commit db673a9033
12 changed files with 57 additions and 57 deletions

View File

@ -376,7 +376,7 @@ class BaseDocument(object):
if clean:
try:
self.clean()
except ValidationError, error:
except ValidationError as error:
errors[NON_FIELD_ERRORS] = error
# Get a list of tuples of field names and their current values
@ -395,9 +395,9 @@ class BaseDocument(object):
field._validate(value, clean=clean)
else:
field._validate(value)
except ValidationError, error:
except ValidationError as error:
errors[field.name] = error.errors or error
except (ValueError, AttributeError, AssertionError), error:
except (ValueError, AttributeError, AssertionError) as error:
errors[field.name] = error
elif field.required and not getattr(field, '_auto_gen', False):
errors[field.name] = ValidationError('Field is required',
@ -712,7 +712,7 @@ class BaseDocument(object):
else field.to_python(value))
if field_name != field.db_field:
del data[field.db_field]
except (AttributeError, ValueError), e:
except (AttributeError, ValueError) as e:
errors_dict[field_name] = e
if errors_dict:

View File

@ -415,9 +415,9 @@ class ComplexBaseField(BaseField):
for k, v in sequence:
try:
self.field._validate(v)
except ValidationError, error:
except ValidationError as error:
errors[k] = error.errors or error
except (ValueError, AssertionError), error:
except (ValueError, AssertionError) as error:
errors[k] = error
if errors:
@ -458,7 +458,7 @@ class ObjectIdField(BaseField):
if not isinstance(value, ObjectId):
try:
return ObjectId(unicode(value))
except Exception, e:
except Exception as e:
# e.message attribute has been deprecated since Python 2.6
self.error(unicode(e))
return value

View File

@ -180,7 +180,7 @@ def get_connection(alias=DEFAULT_CONNECTION_NAME, reconnect=False):
break
_connections[alias] = connection if connection else connection_class(**conn_settings)
except Exception, e:
except Exception as e:
raise ConnectionError("Cannot connect to database %s :\n%s" % (alias, e))
return _connections[alias]

View File

@ -393,10 +393,10 @@ class Document(BaseDocument):
kwargs.update(cascade_kwargs)
kwargs['_refs'] = _refs
self.cascade_save(**kwargs)
except pymongo.errors.DuplicateKeyError, err:
except pymongo.errors.DuplicateKeyError as err:
message = u'Tried to save duplicate unique keys (%s)'
raise NotUniqueError(message % unicode(err))
except pymongo.errors.OperationFailure, err:
except pymongo.errors.OperationFailure as err:
message = 'Could not save document (%s)'
if re.match('^E1100[01] duplicate key', unicode(err)):
# E11000 - duplicate key error index
@ -513,7 +513,7 @@ class Document(BaseDocument):
try:
self._qs.filter(
**self._object_key).delete(write_concern=write_concern, _from_doc_delete=True)
except pymongo.errors.OperationFailure, err:
except pymongo.errors.OperationFailure as err:
message = u'Could not delete document (%s)' % err.message
raise OperationError(message)
signals.post_delete.send(self.__class__, document=self, **signal_kwargs)

View File

@ -156,7 +156,7 @@ class URLField(StringField):
try:
request = urllib2.Request(value)
urllib2.urlopen(request)
except Exception, e:
except Exception as e:
self.error('This URL appears to be a broken link: %s' % e)
@ -350,7 +350,7 @@ class DecimalField(BaseField):
value = unicode(value)
try:
value = decimal.Decimal(value)
except Exception, exc:
except Exception as exc:
self.error('Could not convert value to decimal: %s' % exc)
if self.min_value is not None and value < self.min_value:
@ -1558,7 +1558,7 @@ class ImageGridFsProxy(GridFSProxy):
try:
img = Image.open(file_obj)
img_format = img.format
except Exception, e:
except Exception as e:
raise ValidationError('Invalid image: %s' % e)
# Progressive JPEG
@ -1886,7 +1886,7 @@ class UUIDField(BaseField):
value = str(value)
try:
uuid.UUID(value)
except Exception, exc:
except Exception as exc:
self.error('Could not convert to UUID: %s' % exc)

View File

@ -166,7 +166,7 @@ class BaseQuerySet(object):
queryset._skip, queryset._limit = key.start, key.stop
if key.start and key.stop:
queryset._limit = key.stop - key.start
except IndexError, err:
except IndexError as err:
# PyMongo raises an error if key.start == key.stop, catch it,
# bin it, kill it.
start = key.start or 0
@ -350,10 +350,10 @@ class BaseQuerySet(object):
raw = [doc.to_mongo() for doc in docs]
try:
ids = self._collection.insert(raw, **write_concern)
except pymongo.errors.DuplicateKeyError, err:
except pymongo.errors.DuplicateKeyError as err:
message = 'Could not save document (%s)'
raise NotUniqueError(message % unicode(err))
except pymongo.errors.OperationFailure, err:
except pymongo.errors.OperationFailure as err:
message = 'Could not save document (%s)'
if re.match('^E1100[01] duplicate key', unicode(err)):
# E11000 - duplicate key error index
@ -505,9 +505,9 @@ class BaseQuerySet(object):
return result
elif result:
return result['n']
except pymongo.errors.DuplicateKeyError, err:
except pymongo.errors.DuplicateKeyError as err:
raise NotUniqueError(u'Update failed (%s)' % unicode(err))
except pymongo.errors.OperationFailure, err:
except pymongo.errors.OperationFailure as err:
if unicode(err) == u'multi not coded yet':
message = u'update() method requires MongoDB 1.1.3+'
raise OperationError(message)
@ -615,9 +615,9 @@ class BaseQuerySet(object):
result = queryset._collection.find_and_modify(
query, update, upsert=upsert, sort=sort, remove=remove, new=new,
full_response=full_response, **self._cursor_args)
except pymongo.errors.DuplicateKeyError, err:
except pymongo.errors.DuplicateKeyError as err:
raise NotUniqueError(u"Update failed (%s)" % err)
except pymongo.errors.OperationFailure, err:
except pymongo.errors.OperationFailure as err:
raise OperationError(u"Update failed (%s)" % err)
if full_response:
@ -1643,7 +1643,7 @@ class BaseQuerySet(object):
field = ".".join(f.db_field for f in
document._lookup_field(field.split('.')))
ret.append(field)
except LookUpError, err:
except LookUpError as err:
found = False
for subdoc in subclasses:
try:

View File

@ -57,7 +57,7 @@ def query(_doc_cls=None, **kwargs):
# Switch field names to proper names [set in Field(name='foo')]
try:
fields = _doc_cls._lookup_field(parts)
except Exception, e:
except Exception as e:
raise InvalidQueryError(e)
parts = []
@ -223,7 +223,7 @@ def update(_doc_cls=None, **update):
# Switch field names to proper names [set in Field(name='foo')]
try:
fields = _doc_cls._lookup_field(parts)
except Exception, e:
except Exception as e:
raise InvalidQueryError(e)
parts = []

View File

@ -745,7 +745,7 @@ class InstanceTest(unittest.TestCase):
try:
t.save()
except ValidationError, e:
except ValidationError as e:
expect_msg = "Draft entries may not have a publication date."
self.assertTrue(expect_msg in e.message)
self.assertEqual(e.to_dict(), {'__all__': expect_msg})
@ -784,7 +784,7 @@ class InstanceTest(unittest.TestCase):
t = TestDocument(doc=TestEmbeddedDocument(x=10, y=25, z=15))
try:
t.save()
except ValidationError, e:
except ValidationError as e:
expect_msg = "Value of z != x + y"
self.assertTrue(expect_msg in e.message)
self.assertEqual(e.to_dict(), {'doc': {'__all__': expect_msg}})

View File

@ -60,7 +60,7 @@ class ValidatorErrorTest(unittest.TestCase):
try:
User().validate()
except ValidationError, e:
except ValidationError as e:
self.assertTrue("User:None" in e.message)
self.assertEqual(e.to_dict(), {
'username': 'Field is required',
@ -70,7 +70,7 @@ class ValidatorErrorTest(unittest.TestCase):
user.name = None
try:
user.save()
except ValidationError, e:
except ValidationError as e:
self.assertTrue("User:RossC0" in e.message)
self.assertEqual(e.to_dict(), {
'name': 'Field is required'})
@ -118,7 +118,7 @@ class ValidatorErrorTest(unittest.TestCase):
try:
Doc(id="bad").validate()
except ValidationError, e:
except ValidationError as e:
self.assertTrue("SubDoc:None" in e.message)
self.assertEqual(e.to_dict(), {
"e": {'val': 'OK could not be converted to int'}})
@ -136,7 +136,7 @@ class ValidatorErrorTest(unittest.TestCase):
doc.e.val = "OK"
try:
doc.save()
except ValidationError, e:
except ValidationError as e:
self.assertTrue("Doc:test" in e.message)
self.assertEqual(e.to_dict(), {
"e": {'val': 'OK could not be converted to int'}})

View File

@ -3106,7 +3106,7 @@ class FieldTest(unittest.TestCase):
try:
shirt.validate()
except ValidationError, error:
except ValidationError as error:
# get the validation rules
error_dict = error.to_dict()
self.assertEqual(error_dict['size'], SIZE_MESSAGE)
@ -3494,7 +3494,7 @@ class FieldTest(unittest.TestCase):
self.assertRaises(ValidationError, post.validate)
try:
post.validate()
except ValidationError, error:
except ValidationError as error:
# ValidationError.errors property
self.assertTrue(hasattr(error, 'errors'))
self.assertTrue(isinstance(error.errors, dict))

View File

@ -379,7 +379,7 @@ class FileTest(unittest.TestCase):
try:
t.image.put(f)
self.fail("Should have raised an invalidation error")
except ValidationError, e:
except ValidationError as e:
self.assertEqual("%s" % e, "Invalid image: cannot identify image file %s" % f)
t = TestImage()

View File

@ -41,7 +41,7 @@ class ConnectionTest(unittest.TestCase):
conn = connect(db='mongoenginetest',
host="mongodb://localhost/mongoenginetest?replicaSet=rs",
read_preference=READ_PREF)
except ConnectionError, e:
except ConnectionError as e:
return
if not isinstance(conn, CONN_CLASS):