Files
notifications-admin/app/models/__init__.py
Chris Hill-Scott 89c63e3243 Remove custom getattr implementation from JSONModel
We wrote custom `__getattr__` and `__getitem__` implementation to make
it easier to find code that was accessing fields in the dictionary that
we weren’t aware of. See this commit for details:
b48305c50d

Now that no view-layer code accesses the service dictionary directly we
don’t need to support this behaviour any more. By removing it we can
make the model code simpler, and closer to the `SerialisedModel` it
inherits from.

It still needs some custom implementation because:
- a lot of our test fixtures are lazy and don’t set up all the expected
  fields, so we need to account for fields sometimes being present in
  the underlying dictionary and sometimes not
- we often implement a property that has the same name as one of the
  fields in the JSON, so we have to be careful not to try to override
  this property with the value from the underlying JSON
2020-10-19 15:52:51 +01:00

44 lines
1.0 KiB
Python

from abc import abstractmethod
from flask import abort
from notifications_utils.serialised_model import (
SerialisedModel,
SerialisedModelCollection,
)
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 and not hasattr(self, property):
setattr(self, property, self._dict[property])
def __bool__(self):
return self._dict != {}
def __hash__(self):
return hash(self.id)
def __eq__(self, other):
return self.id == other.id
def _get_by_id(self, things, id):
try:
return next(thing for thing in things if thing['id'] == str(id))
except StopIteration:
abort(404)
class ModelList(SerialisedModelCollection):
@property
@abstractmethod
def client_method(self):
pass
def __init__(self, *args):
self.items = self.client_method(*args)