Merge pull request #3687 from alphagov/remove-custom-getattr

Remove custom `getattr` implementation from JSONModel
This commit is contained in:
Chris Hill-Scott
2020-10-28 10:46:13 +00:00
committed by GitHub
5 changed files with 15 additions and 43 deletions

View File

@@ -12,6 +12,9 @@ class JSONModel(SerialisedModel):
def __init__(self, _dict):
# in the case of a bad request _dict may be `None`
self._dict = _dict or {}
for property in self.ALLOWED_PROPERTIES:
if property in self._dict:
setattr(self, property, self._dict[property])
def __bool__(self):
return self._dict != {}
@@ -19,37 +22,9 @@ class JSONModel(SerialisedModel):
def __hash__(self):
return hash(self.id)
def __dir__(self):
return super().__dir__() + list(sorted(self.ALLOWED_PROPERTIES))
def __eq__(self, other):
return self.id == other.id
def __getattribute__(self, attr):
# Eventually we should remove this custom implementation in
# favour of looping over self.ALLOWED_PROPERTIES in __init__
try:
return super().__getattribute__(attr)
except AttributeError as e:
# Re-raise any `AttributeError`s that are not directly on
# this object because they indicate an underlying exception
# that we dont want to swallow
if str(e) != "'{}' object has no attribute '{}'".format(
self.__class__.__name__, attr
):
raise e
if attr in super().__getattribute__('ALLOWED_PROPERTIES'):
return super().__getattribute__('_dict')[attr]
raise AttributeError((
"'{}' object has no attribute '{}' and '{}' is not a field "
"in the underlying JSON"
).format(
self.__class__.__name__, attr, attr
))
def _get_by_id(self, things, id):
try:
return next(thing for thing in things if thing['id'] == str(id))

View File

@@ -25,11 +25,9 @@ class Job(JSONModel):
ALLOWED_PROPERTIES = {
'id',
'service',
'template',
'template_version',
'original_file_name',
'created_at',
'processing_started',
'notification_count',
'created_by',
'template_type',

View File

@@ -31,11 +31,9 @@ class Service(JSONModel):
ALLOWED_PROPERTIES = {
'active',
'contact_link',
'email_branding',
'email_from',
'id',
'inbound_api',
'letter_branding',
'message_limit',
'rate_limit',
'name',

View File

@@ -39,7 +39,6 @@ class User(JSONModel, UserMixin):
'mobile_number',
'password_changed_at',
'permissions',
'platform_admin',
'state',
}