From 91db3e58e1813d49c91bc8d1076f435b686a25a3 Mon Sep 17 00:00:00 2001 From: Andrew Yatsura Date: Sun, 3 Jan 2021 21:08:37 +0200 Subject: [PATCH] Resolve #56 --- resources/Map.py | 41 +++++++++++++++++++++++++++++------------ 1 file changed, 29 insertions(+), 12 deletions(-) diff --git a/resources/Map.py b/resources/Map.py index addf3dc..3e28ccc 100644 --- a/resources/Map.py +++ b/resources/Map.py @@ -1,27 +1,44 @@ from datetime import datetime, timedelta from os import environ -from common.convert_types_to_names import convert_types_to_names from flask_restful import Resource -from models import AreaModel +from models import AreaModel, SensorModel, SensorDataModel from sqlalchemy import desc class Map(Resource): def get(self): - maxdate = datetime.now() - timedelta(hours=int(environ.get('MAX_RECORD_HOURS'))) + latest_records = self._get_latest_records() + aqi_records = [] - areas = AreaModel.query.order_by(desc(AreaModel.created)).filter( - AreaModel.created >= maxdate).all() + for record in latest_records: + aqi_record = AreaModel.query \ + .order_by( + AreaModel.created.desc() + ).filter_by( + latitude=record.latitude + ).filter_by( + longitude=record.longitude + ).first() - areas_coords = [] - areas_list = [] + if aqi_record: + aqi_records.append(aqi_record.as_dict()) - for area in areas: - if (area.latitude, area.longitude) in areas_coords: + return aqi_records + + def _get_latest_records(self): + sensors = SensorModel.query.all() + + latest_records = [] + for sensor in sensors: + record = SensorDataModel.query.order_by(SensorDataModel.recorded.desc()).filter_by( + internal_id=sensor.external_id).first() + + if not record: continue - areas_coords.append((area.latitude, area.longitude)) - areas_list.append(convert_types_to_names(area)) + timedelta = datetime.now() - record.recorded + if (timedelta.seconds // 3600) <= int(environ.get('MAX_RECORD_HOURS')): + latest_records.append(record) - return areas_list + return latest_records