def get_recent(self, site_id: int, unit: MetricUnit,
                   time: datetime.datetime, limit: int,
                   **kwargs) -> List[Measurement]:
        metric_key = self.key_schema.timeseries_key(site_id, unit)
        time_ms = unix_milliseconds(time)
        initial_timestamp = time_ms - (limit * 60) * 1000
        values = self.redis.range(metric_key, initial_timestamp,
                                  time_ms)  # type: ignore

        return [
            Measurement(site_id=site_id,
                        metric_unit=unit,
                        timestamp=value[0] / 1000,
                        value=value[1]) for value in islice(values, limit)
        ]
Beispiel #2
0
    def _get_measurements_for_date(self, site_id: int, date: datetime.datetime,
                                   unit: MetricUnit,
                                   count: int) -> List[Measurement]:
        """
        Return up to `count` elements from the sorted set corresponding to
        the site_id, date, and metric unit specified here.
        """
        measurements = []

        # Get the metric key for the day implied by the date.
        # metric:[unit-name]:[year-month-day]:[site-id]
        # e.g.: metrics:whU:2020-01-01:1
        key = self.key_schema.day_metric_key(site_id, unit, date)

        # Get `count` number of items from the end of the sorted set.
        metrics = self.redis.zrevrange(key, 0, count - 1, withscores=True)

        for metric in metrics:
            # `zrevrange()` returns (member, score) tuples, and within these
            # tuples, "member" is a string of the form [measurement]:[minute].
            # The MeasurementMinute class abstracts this for us.
            mm = MeasurementMinute.from_zset_value(metric[0])

            # Derive the datetime for the measurement using the date and
            # the minute of the day. Note that this always returns datetime
            # objects whose seconds value is zero.
            date = self._get_date_from_day_minute(date, mm.minute_of_day)

            # Add a new measurement to the list of measurements.
            measurements.append(
                Measurement(site_id=site_id,
                            metric_unit=unit,
                            timestamp=date,
                            value=mm.measurement))

        return measurements