Repository navigation
Expand file tree
/
Copy pathdatetime.py
More file actions
76 lines (64 loc) · 2.5 KB
/
Copy pathdatetime.py
File metadata and controls
76 lines (64 loc) · 2.5 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
from __future__ import annotations
import datetime
from typing import Any, ClassVar
from attr import define, field
from ... import schema as oai
from ...strings import PythonCode, PythonIdentifier
from ..errors import PropertyError
from .protocol import PropertyProtocol, Value, convert_example
@define
class DateTimeProperty(PropertyProtocol):
"""
A property of type datetime.datetime
"""
name: oai.UntrustedString
required: bool
default: Value | None
python_name: PythonIdentifier
description: oai.UntrustedString | None
example: oai.UntrustedString | None = field(converter=convert_example)
_type_string: ClassVar[str] = "datetime.datetime"
_json_type_string: ClassVar[str] = "str"
template: ClassVar[str] = "datetime_property.py.jinja"
@classmethod
def build(
cls,
name: oai.UntrustedString,
required: bool,
default: Any,
python_name: PythonIdentifier,
description: oai.UntrustedString | None,
example: Any,
) -> DateTimeProperty | PropertyError:
checked_default = cls.convert_value(default)
if isinstance(checked_default, PropertyError):
return checked_default
return DateTimeProperty(
name=name,
required=required,
default=checked_default,
python_name=python_name,
description=description,
example=example,
)
@classmethod
def convert_value(cls, value: Any) -> Value | PropertyError | None:
if value is None or isinstance(value, Value):
return value
if isinstance(value, str):
try:
datetime.datetime.fromisoformat(value) # make sure it's a valid value
except ValueError as e:
return PropertyError(f"Invalid datetime: {e}")
return Value(python_code=PythonCode(f"datetime.datetime.fromisoformat({value!r})"), raw_value=value)
return PropertyError(f"Cannot convert {value} to a datetime")
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"})
return imports