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

View File

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

View File

@ -180,7 +180,7 @@ def get_connection(alias=DEFAULT_CONNECTION_NAME, reconnect=False):
break break
_connections[alias] = connection if connection else connection_class(**conn_settings) _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)) raise ConnectionError("Cannot connect to database %s :\n%s" % (alias, e))
return _connections[alias] return _connections[alias]

View File

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

View File

@ -156,7 +156,7 @@ class URLField(StringField):
try: try:
request = urllib2.Request(value) request = urllib2.Request(value)
urllib2.urlopen(request) urllib2.urlopen(request)
except Exception, e: except Exception as e:
self.error('This URL appears to be a broken link: %s' % e) self.error('This URL appears to be a broken link: %s' % e)
@ -350,7 +350,7 @@ class DecimalField(BaseField):
value = unicode(value) value = unicode(value)
try: try:
value = decimal.Decimal(value) value = decimal.Decimal(value)
except Exception, exc: except Exception as exc:
self.error('Could not convert value to decimal: %s' % exc) self.error('Could not convert value to decimal: %s' % exc)
if self.min_value is not None and value < self.min_value: if self.min_value is not None and value < self.min_value:
@ -1558,7 +1558,7 @@ class ImageGridFsProxy(GridFSProxy):
try: try:
img = Image.open(file_obj) img = Image.open(file_obj)
img_format = img.format img_format = img.format
except Exception, e: except Exception as e:
raise ValidationError('Invalid image: %s' % e) raise ValidationError('Invalid image: %s' % e)
# Progressive JPEG # Progressive JPEG
@ -1886,7 +1886,7 @@ class UUIDField(BaseField):
value = str(value) value = str(value)
try: try:
uuid.UUID(value) uuid.UUID(value)
except Exception, exc: except Exception as exc:
self.error('Could not convert to UUID: %s' % 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 queryset._skip, queryset._limit = key.start, key.stop
if key.start and key.stop: if key.start and key.stop:
queryset._limit = key.stop - key.start queryset._limit = key.stop - key.start
except IndexError, err: except IndexError as err:
# PyMongo raises an error if key.start == key.stop, catch it, # PyMongo raises an error if key.start == key.stop, catch it,
# bin it, kill it. # bin it, kill it.
start = key.start or 0 start = key.start or 0
@ -350,10 +350,10 @@ class BaseQuerySet(object):
raw = [doc.to_mongo() for doc in docs] raw = [doc.to_mongo() for doc in docs]
try: try:
ids = self._collection.insert(raw, **write_concern) ids = self._collection.insert(raw, **write_concern)
except pymongo.errors.DuplicateKeyError, err: except pymongo.errors.DuplicateKeyError as err:
message = 'Could not save document (%s)' message = 'Could not save document (%s)'
raise NotUniqueError(message % unicode(err)) raise NotUniqueError(message % unicode(err))
except pymongo.errors.OperationFailure, err: except pymongo.errors.OperationFailure as err:
message = 'Could not save document (%s)' message = 'Could not save document (%s)'
if re.match('^E1100[01] duplicate key', unicode(err)): if re.match('^E1100[01] duplicate key', unicode(err)):
# E11000 - duplicate key error index # E11000 - duplicate key error index
@ -505,9 +505,9 @@ class BaseQuerySet(object):
return result return result
elif result: elif result:
return result['n'] return result['n']
except pymongo.errors.DuplicateKeyError, err: except pymongo.errors.DuplicateKeyError as err:
raise NotUniqueError(u'Update failed (%s)' % unicode(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': if unicode(err) == u'multi not coded yet':
message = u'update() method requires MongoDB 1.1.3+' message = u'update() method requires MongoDB 1.1.3+'
raise OperationError(message) raise OperationError(message)
@ -615,9 +615,9 @@ class BaseQuerySet(object):
result = queryset._collection.find_and_modify( result = queryset._collection.find_and_modify(
query, update, upsert=upsert, sort=sort, remove=remove, new=new, query, update, upsert=upsert, sort=sort, remove=remove, new=new,
full_response=full_response, **self._cursor_args) 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) 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) raise OperationError(u"Update failed (%s)" % err)
if full_response: if full_response:
@ -1643,7 +1643,7 @@ class BaseQuerySet(object):
field = ".".join(f.db_field for f in field = ".".join(f.db_field for f in
document._lookup_field(field.split('.'))) document._lookup_field(field.split('.')))
ret.append(field) ret.append(field)
except LookUpError, err: except LookUpError as err:
found = False found = False
for subdoc in subclasses: for subdoc in subclasses:
try: try:

View File

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

View File

@ -745,7 +745,7 @@ class InstanceTest(unittest.TestCase):
try: try:
t.save() t.save()
except ValidationError, e: except ValidationError as e:
expect_msg = "Draft entries may not have a publication date." expect_msg = "Draft entries may not have a publication date."
self.assertTrue(expect_msg in e.message) self.assertTrue(expect_msg in e.message)
self.assertEqual(e.to_dict(), {'__all__': expect_msg}) 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)) t = TestDocument(doc=TestEmbeddedDocument(x=10, y=25, z=15))
try: try:
t.save() t.save()
except ValidationError, e: except ValidationError as e:
expect_msg = "Value of z != x + y" expect_msg = "Value of z != x + y"
self.assertTrue(expect_msg in e.message) self.assertTrue(expect_msg in e.message)
self.assertEqual(e.to_dict(), {'doc': {'__all__': expect_msg}}) self.assertEqual(e.to_dict(), {'doc': {'__all__': expect_msg}})
@ -3118,17 +3118,17 @@ class InstanceTest(unittest.TestCase):
p4 = Person.objects()[0] p4 = Person.objects()[0]
p4.save() p4.save()
self.assertEquals(p4.height, 189) self.assertEquals(p4.height, 189)
# However the default will not be fixed in DB # However the default will not be fixed in DB
self.assertEquals(Person.objects(height=189).count(), 0) self.assertEquals(Person.objects(height=189).count(), 0)
# alter DB for the new default # alter DB for the new default
coll = Person._get_collection() coll = Person._get_collection()
for person in Person.objects.as_pymongo(): for person in Person.objects.as_pymongo():
if 'height' not in person: if 'height' not in person:
person['height'] = 189 person['height'] = 189
coll.save(person) coll.save(person)
self.assertEquals(Person.objects(height=189).count(), 1) self.assertEquals(Person.objects(height=189).count(), 1)
def test_from_son(self): def test_from_son(self):

View File

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

View File

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

View File

@ -297,66 +297,66 @@ class FileTest(unittest.TestCase):
test_file = TestFile() test_file = TestFile()
self.assertFalse(test_file.the_file in [{"test": 1}]) self.assertFalse(test_file.the_file in [{"test": 1}])
def test_file_disk_space(self): def test_file_disk_space(self):
""" Test disk space usage when we delete/replace a file """ """ Test disk space usage when we delete/replace a file """
class TestFile(Document): class TestFile(Document):
the_file = FileField() the_file = FileField()
text = b('Hello, World!') text = b('Hello, World!')
content_type = 'text/plain' content_type = 'text/plain'
testfile = TestFile() testfile = TestFile()
testfile.the_file.put(text, content_type=content_type, filename="hello") testfile.the_file.put(text, content_type=content_type, filename="hello")
testfile.save() testfile.save()
# Now check fs.files and fs.chunks # Now check fs.files and fs.chunks
db = TestFile._get_db() db = TestFile._get_db()
files = db.fs.files.find() files = db.fs.files.find()
chunks = db.fs.chunks.find() chunks = db.fs.chunks.find()
self.assertEquals(len(list(files)), 1) self.assertEquals(len(list(files)), 1)
self.assertEquals(len(list(chunks)), 1) self.assertEquals(len(list(chunks)), 1)
# Deleting the docoument should delete the files # Deleting the docoument should delete the files
testfile.delete() testfile.delete()
files = db.fs.files.find() files = db.fs.files.find()
chunks = db.fs.chunks.find() chunks = db.fs.chunks.find()
self.assertEquals(len(list(files)), 0) self.assertEquals(len(list(files)), 0)
self.assertEquals(len(list(chunks)), 0) self.assertEquals(len(list(chunks)), 0)
# Test case where we don't store a file in the first place # Test case where we don't store a file in the first place
testfile = TestFile() testfile = TestFile()
testfile.save() testfile.save()
files = db.fs.files.find() files = db.fs.files.find()
chunks = db.fs.chunks.find() chunks = db.fs.chunks.find()
self.assertEquals(len(list(files)), 0) self.assertEquals(len(list(files)), 0)
self.assertEquals(len(list(chunks)), 0) self.assertEquals(len(list(chunks)), 0)
testfile.delete() testfile.delete()
files = db.fs.files.find() files = db.fs.files.find()
chunks = db.fs.chunks.find() chunks = db.fs.chunks.find()
self.assertEquals(len(list(files)), 0) self.assertEquals(len(list(files)), 0)
self.assertEquals(len(list(chunks)), 0) self.assertEquals(len(list(chunks)), 0)
# Test case where we overwrite the file # Test case where we overwrite the file
testfile = TestFile() testfile = TestFile()
testfile.the_file.put(text, content_type=content_type, filename="hello") testfile.the_file.put(text, content_type=content_type, filename="hello")
testfile.save() testfile.save()
text = b('Bonjour, World!') text = b('Bonjour, World!')
testfile.the_file.replace(text, content_type=content_type, filename="hello") testfile.the_file.replace(text, content_type=content_type, filename="hello")
testfile.save() testfile.save()
files = db.fs.files.find() files = db.fs.files.find()
chunks = db.fs.chunks.find() chunks = db.fs.chunks.find()
self.assertEquals(len(list(files)), 1) self.assertEquals(len(list(files)), 1)
self.assertEquals(len(list(chunks)), 1) self.assertEquals(len(list(chunks)), 1)
testfile.delete() testfile.delete()
files = db.fs.files.find() files = db.fs.files.find()
chunks = db.fs.chunks.find() chunks = db.fs.chunks.find()
self.assertEquals(len(list(files)), 0) self.assertEquals(len(list(files)), 0)
@ -379,7 +379,7 @@ class FileTest(unittest.TestCase):
try: try:
t.image.put(f) t.image.put(f)
self.fail("Should have raised an invalidation error") 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) self.assertEqual("%s" % e, "Invalid image: cannot identify image file %s" % f)
t = TestImage() t = TestImage()

View File

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