-
-
Notifications
You must be signed in to change notification settings - Fork 277
Expand file tree
/
Copy pathdate.py
More file actions
77 lines (65 loc) · 2.4 KB
/
date.py
File metadata and controls
77 lines (65 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
from __future__ import annotations
from typing import Any, ClassVar
from attr import define
from dateutil.parser import isoparse
from ...utils import PythonIdentifier
from ... import schema as oai
from ..errors import PropertyError
from .protocol import PropertyProtocol, Value
@define
class DateProperty(PropertyProtocol):
"""A property of type datetime.date"""
name: str
required: bool
default: Value | None
python_name: PythonIdentifier
description: str | None
example: str | None
data: oai.Schema
_type_string: ClassVar[str] = "datetime.date"
_json_type_string: ClassVar[str] = "str"
template: ClassVar[str] = "date_property.py.jinja"
@classmethod
def build(
cls,
name: str,
required: bool,
default: Any,
python_name: PythonIdentifier,
description: str | None,
example: str | None,
data: oai.Schema
) -> DateProperty | PropertyError:
checked_default = cls.convert_value(default)
if isinstance(checked_default, PropertyError):
return checked_default
return DateProperty(
name=name,
required=required,
default=checked_default,
python_name=python_name,
description=description,
example=example,
data=data,
)
@classmethod
def convert_value(cls, value: Any) -> Value | None | PropertyError:
if isinstance(value, Value) or value is None:
return value
if isinstance(value, str):
try:
isoparse(value).date() # make sure it's a valid value
except ValueError as e:
return PropertyError(f"Invalid date: {e}")
return Value(python_code=f"isoparse({value!r}).date()", raw_value=value)
return PropertyError(f"Cannot convert {value} to a date")
def get_imports(self, *, prefix: str) -> set[str]:
"""
Get a set of import strings that should be included when this property is used somewhere
Args:
prefix: A prefix to put before any relative (local) module names. This should be the number of . to get
back to the root of the generated client.
"""
imports = super().get_imports(prefix=prefix)
imports.update({"import datetime", "from typing import cast", "from dateutil.parser import isoparse"})
return imports