Skip to content

Commit

Permalink
extend timedelta parsing for pydantic fields
Browse files Browse the repository at this point in the history
  • Loading branch information
steersbob committed Jun 7, 2024
1 parent d4e4622 commit 6931b71
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 11 deletions.
20 changes: 12 additions & 8 deletions brewblox_history/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ def parse_duration(value: DurationSrc_) -> timedelta:

try:
value = float(value)
except TypeError:
value = None
except ValueError:
value = timeparse(value) or value

Expand All @@ -39,7 +41,7 @@ def parse_datetime(value: DatetimeSrc_) -> datetime | None:
return pydantic_datetime_validator.validate_python(value)


Duration_ = Annotated[timedelta, BeforeValidator(parse_duration)]
loose_timedelta = Annotated[timedelta, BeforeValidator(parse_duration)]


def flatten(d, parent_key=''):
Expand Down Expand Up @@ -88,11 +90,11 @@ class ServiceConfig(BaseSettings):
history_topic: str = 'brewcast/history'
datastore_topic: str = 'brewcast/datastore'

ranges_interval: Duration_ = timedelta(seconds=10)
metrics_interval: Duration_ = timedelta(seconds=10)
minimum_step: Duration_ = timedelta(seconds=10)
ranges_interval: loose_timedelta = timedelta(seconds=10)
metrics_interval: loose_timedelta = timedelta(seconds=10)
minimum_step: loose_timedelta = timedelta(seconds=10)

query_duration_default: Duration_ = timedelta(days=1)
query_duration_default: loose_timedelta = timedelta(days=1)
query_desired_points: int = 1000


Expand Down Expand Up @@ -148,12 +150,14 @@ class DatastoreDeleteResponse(BaseModel):


class TimeSeriesFieldsQuery(BaseModel):
duration: str = Field('1d', examples=['10m', '1d'])
duration: loose_timedelta = Field(timedelta(days=1),
examples=['10m', '1d'])


class TimeSeriesMetricsQuery(BaseModel):
fields: list[str]
duration: str = Field('10m', examples=['10m', '1d'])
duration: loose_timedelta = Field(timedelta(minutes=10),
examples=['10m', '1d'])


class TimeSeriesMetric(BaseModel):
Expand All @@ -166,7 +170,7 @@ class TimeSeriesRangesQuery(BaseModel):
fields: list[str] = Field(examples=[['spark-one/sensor/value[degC]']])
start: datetime | None = Field(None, examples=['2020-01-01T20:00:00.000Z'])
end: datetime | None = Field(None, examples=['2030-01-01T20:00:00.000Z'])
duration: str | None = Field(None, examples=['1d'])
duration: loose_timedelta | None = Field(None, examples=['1d'])


class TimeSeriesRangeValue(NamedTuple):
Expand Down
2 changes: 1 addition & 1 deletion brewblox_history/victoria.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ async def _json_query(self, query: str, url: str):
return resp.json()

async def fields(self, args: TimeSeriesFieldsQuery) -> list[str]:
query = f'match[]={{__name__!=""}}&start={args.duration}'
query = f'match[]={{__name__!=""}}&start={args.duration.total_seconds()}s'
LOGGER.debug(query)
result = await self._json_query(query, '/api/v1/series')
retv = [
Expand Down
1 change: 0 additions & 1 deletion test/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@ def config(monkeypatch: pytest.MonkeyPatch,
redis_port=docker_services.port_for('redis', 6379),
victoria_host='localhost',
victoria_port=docker_services.port_for('victoria', 8428),
ranges_interval='10s',
)
monkeypatch.setattr(utils, 'get_config', lambda: cfg)
yield cfg
Expand Down
2 changes: 1 addition & 1 deletion test/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def test_parse_duration():
with pytest.raises(ValidationError):
utils.parse_duration('')

with pytest.raises(TypeError):
with pytest.raises(ValidationError):
utils.parse_duration(None)


Expand Down

0 comments on commit 6931b71

Please sign in to comment.