diff --git a/ereuse_devicehub/resources/metric/views.py b/ereuse_devicehub/resources/metric/views.py index 0b16c8a8..561150da 100644 --- a/ereuse_devicehub/resources/metric/views.py +++ b/ereuse_devicehub/resources/metric/views.py @@ -1,17 +1,13 @@ from flask import request, g, jsonify -from ereuse_devicehub.resources.action import schemas +from contextlib import suppress from teal.resource import View +from ereuse_devicehub.resources.action import schemas from ereuse_devicehub.resources.action.models import Allocate, Live, Action, ToRepair, ToPrepare from ereuse_devicehub.resources.device import models as m from ereuse_devicehub.resources.metric.schema import Metric -def last_action(dev, action): - act = [e for e in reversed(dev.actions) if isinstance(e, action)] - return act[0] if act else None - - class MetricsView(View): def find(self, args: dict): @@ -32,8 +28,12 @@ class MetricsView(View): devices = m.Device.query.filter(m.Device.allocated==True) count = 0 for dev in devices: - live = last_action(dev, Live) - allocate = last_action(dev, Allocate) + live = allocate = None + with suppress(LookupError): + live = dev.last_action_of(Live) + with suppress(LookupError): + allocate = dev.last_action_of(Allocate) + if not live: continue if allocate and allocate.created > live.created: