|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import re |
| 4 | +from datetime import date, datetime, timedelta, timezone |
| 5 | +from typing import Any |
| 6 | + |
| 7 | +from timessquare.exceptions import PageParameterValueCastingError |
| 8 | + |
| 9 | +from ._datedynamicdefault import DateDynamicDefault |
| 10 | +from ._schemabase import PageParameterSchema |
| 11 | + |
| 12 | +__all__ = ["DayObsDateParameterSchema"] |
| 13 | + |
| 14 | + |
| 15 | +class DayObsDateParameterSchema(PageParameterSchema): |
| 16 | + """A parameter schema for the custom Rubin DayObs date format with dashes. |
| 17 | +
|
| 18 | + DayObsDate is defined as a date in the UTC-12 timezone with the string |
| 19 | + representation formatted as YYYY-MM-DD. Times Square parameters validate |
| 20 | + dayobs-date parameters as strings, but the Python assignment returns a |
| 21 | + datetime.date instance. |
| 22 | + """ |
| 23 | + |
| 24 | + tz = timezone(-timedelta(hours=12)) |
| 25 | + """The timezone for DayObs parameters, UTC-12.""" |
| 26 | + |
| 27 | + @property |
| 28 | + def strict_schema(self) -> dict[str, Any]: |
| 29 | + """Get the JSON schema without the custom format.""" |
| 30 | + schema = super().strict_schema |
| 31 | + # Add a basic regex pattern to validate the YYYY-MM-DD format |
| 32 | + schema["pattern"] = r"^\d{4}-\d{2}-\d{2}$" |
| 33 | + return schema |
| 34 | + |
| 35 | + def validate_default(self) -> bool: |
| 36 | + """Validate the default value for the parameter. |
| 37 | +
|
| 38 | + Returns |
| 39 | + ------- |
| 40 | + bool |
| 41 | + True if the default is valid, False otherwise. |
| 42 | + """ |
| 43 | + if "X-Dynamic-Default" in self.schema: |
| 44 | + try: |
| 45 | + DateDynamicDefault(self.schema["X-Dynamic-Default"]) |
| 46 | + except ValueError: |
| 47 | + return False |
| 48 | + else: |
| 49 | + return True |
| 50 | + elif "default" in self.schema: |
| 51 | + try: |
| 52 | + self.cast_value(self.schema["default"]) |
| 53 | + except PageParameterValueCastingError: |
| 54 | + return False |
| 55 | + else: |
| 56 | + return True |
| 57 | + else: |
| 58 | + return False |
| 59 | + |
| 60 | + def cast_value(self, v: Any) -> date: |
| 61 | + """Cast a value to its Python type.""" |
| 62 | + try: |
| 63 | + # Parse a YYYY-MM-DD string, date object, or datetime object |
| 64 | + if isinstance(v, str): |
| 65 | + return self._cast_string(v) |
| 66 | + elif isinstance(v, datetime): |
| 67 | + # Check datetime before date because of inheritance |
| 68 | + return self._cast_datetime(v) |
| 69 | + elif isinstance(v, date): |
| 70 | + return self._cast_date(v) |
| 71 | + else: |
| 72 | + raise PageParameterValueCastingError.for_value(v, "date") |
| 73 | + except Exception as e: |
| 74 | + raise PageParameterValueCastingError.for_value(v, "date") from e |
| 75 | + |
| 76 | + def _cast_string(self, v: str) -> date: |
| 77 | + """Cast a string value to the date format.""" |
| 78 | + match = re.match(r"^\d{4}-\d{2}-\d{2}$", v) |
| 79 | + if not match: |
| 80 | + raise ValueError(f"Invalid YYYY-MM-DD format: {v}") |
| 81 | + |
| 82 | + year = int(v[:4]) |
| 83 | + month = int(v[5:7]) |
| 84 | + day = int(v[8:10]) |
| 85 | + return date(year, month, day) |
| 86 | + |
| 87 | + def _cast_date(self, v: date) -> date: |
| 88 | + """Cast a date object directly (no conversion needed).""" |
| 89 | + return v |
| 90 | + |
| 91 | + def _cast_datetime(self, v: datetime) -> date: |
| 92 | + """Cast a datetime object to the DayObs date format.""" |
| 93 | + if v.tzinfo is not None: |
| 94 | + # Convert to UTC-12 timezone |
| 95 | + v = v.astimezone(self.tz) |
| 96 | + else: |
| 97 | + # If no timezone info, assume it's in UTC-12 |
| 98 | + v = v.replace(tzinfo=self.tz) |
| 99 | + return v.date() |
| 100 | + |
| 101 | + def create_python_imports(self) -> list[str]: |
| 102 | + return ["import datetime"] |
| 103 | + |
| 104 | + def create_python_assignment(self, name: str, value: Any) -> str: |
| 105 | + date_value = self.cast_value(value) |
| 106 | + str_value = date_value.isoformat() |
| 107 | + return f'{name} = datetime.date.fromisoformat("{str_value}")' |
| 108 | + |
| 109 | + def create_json_value(self, value: Any) -> str: |
| 110 | + return self.cast_value(value).isoformat() |
| 111 | + |
| 112 | + def create_qs_value(self, value: Any) -> str: |
| 113 | + return self.cast_value(value).isoformat() |
| 114 | + |
| 115 | + @property |
| 116 | + def default(self) -> date: |
| 117 | + if "X-Dynamic-Default" in self.schema: |
| 118 | + dynamic_default = DateDynamicDefault( |
| 119 | + self.schema["X-Dynamic-Default"] |
| 120 | + ) |
| 121 | + return dynamic_default(datetime.now(tz=self.tz).date()) |
| 122 | + return self.cast_value(self.schema["default"]) |
0 commit comments